| 1 | // Package seal is the app's only encryption surface. |
| 2 | // |
| 3 | // The one rule: a card's values, its labels and its references are sealed |
| 4 | // at rest, and the durable file never holds a readable one. The DEK |
| 5 | // arrives as platform config and is never written to the database it |
| 6 | // decrypts. |
| 7 | // |
| 8 | // Purpose keys are derived with HKDF so a value sealed as a field value |
| 9 | // cannot be opened as a field label. That is not paranoia: they are rows of |
| 10 | // adjacent tables, and a bug that swapped them would be invisible without |
| 11 | // this. |
| 12 | // |
| 13 | // This package is deliberately a near-copy of memoria's |
| 14 | // internal/memoria/seal, which says the same of Sheets'. Sharing it would |
| 15 | // mean a module all three depend on, which is a coordination cost the |
| 16 | // suite has not paid; the construction being identical is what matters. |
| 17 | // **Three copies is the point at which that trade is worth re-examining, |
| 18 | // and this comment is the record that it was noticed rather than missed.** |
| 19 | // |
| 20 | // The HKDF info string is app-namespaced — "oficina/fichas:" — so the same |
| 21 | // DEK under two apps derives different keys. It must never be changed: it |
| 22 | // is baked into every byte already sealed. |
| 23 | package seal |
| 24 | |
| 25 | import ( |
| 26 | "crypto/aes" |
| 27 | "crypto/cipher" |
| 28 | "crypto/hmac" |
| 29 | "crypto/rand" |
| 30 | "crypto/sha256" |
| 31 | "encoding/hex" |
| 32 | "errors" |
| 33 | "hash" |
| 34 | "io" |
| 35 | "sync" |
| 36 | |
| 37 | "golang.org/x/crypto/hkdf" |
| 38 | ) |
| 39 | |
| 40 | // Purposes. One per kind of thing sealed, so a mix-up cannot decrypt. |
| 41 | const ( |
| 42 | // PurposeLabel seals what a person reads for a card type or a field — |
| 43 | // "Customer", "Next action". Sealed even for the built-in catalogue |
| 44 | // (§4.3): a label that is sometimes plaintext is a rule nobody can |
| 45 | // apply, and a user-added type's label is the user's own words. |
| 46 | PurposeLabel = "type.label" |
| 47 | |
| 48 | // PurposeValue seals a field's value on a card or an entry. The |
| 49 | // largest class by far, and the reason this package exists. |
| 50 | PurposeValue = "field.value" |
| 51 | |
| 52 | // PurposeEventPayload seals the before/after values in the change log. |
| 53 | // Named to match Sheets' "event.payload" because §5 takes that table |
| 54 | // field for field; the name travelling with the shape is deliberate. |
| 55 | // |
| 56 | // This is the purpose whose ciphertext is TOMBSTONED on erasure while |
| 57 | // its row survives (§5). Nothing else here is erased in place. |
| 58 | PurposeEventPayload = "event.payload" |
| 59 | |
| 60 | // PurposeRefTarget seals a reference's (app, instance, item). |
| 61 | // |
| 62 | // REVERSIBLE, unlike a print: resolving a reference means handing the |
| 63 | // item id back to the app it came from, and an HMAC cannot be handed |
| 64 | // back. Sealed rather than plaintext because of §9 — a readable |
| 65 | // reference to a non-team item is at-rest knowledge, in a second app, |
| 66 | // that a private item exists. That is the leak S1's visibility flag |
| 67 | // was removed to prevent. |
| 68 | PurposeRefTarget = "ref.target" |
| 69 | ) |
| 70 | |
| 71 | // printPurpose returns the one-way purpose for a field's print. |
| 72 | // |
| 73 | // **Scoped per field key, not shared.** A single print purpose across every |
| 74 | // field would make equality comparable ACROSS fields: an observer holding |
| 75 | // the file could see that one card's value in field A equals another's in |
| 76 | // field B without opening either. Scoping costs nothing and removes the |
| 77 | // question. fieldKey is this app's opaque constant, never the user's words. |
| 78 | func printPurpose(fieldKey string) string { return "field.print:" + fieldKey } |
| 79 | |
| 80 | // refPrintPurpose is printPurpose's twin for reference dedupe. |
| 81 | const refPrintPurpose = "ref.print" |
| 82 | |
| 83 | func sha256New() hash.Hash { return sha256.New() } |
| 84 | |
| 85 | // Sealer holds the data encryption key. One per process. |
| 86 | // |
| 87 | // It caches each purpose's derived AEAD. Deriving one is an HKDF expand, a |
| 88 | // key schedule and a GCM table — about 1.5µs, which was nearly all of the |
| 89 | // cost of an Open, paid again for every value on every list page. The key |
| 90 | // for a purpose never changes, so it is derived once. A GCM AEAD holds only |
| 91 | // read-only state after construction and is safe for concurrent Seal and |
| 92 | // Open, which is how crypto/tls uses one per direction of a connection. |
| 93 | type Sealer struct { |
| 94 | dek []byte |
| 95 | |
| 96 | mu sync.RWMutex |
| 97 | aeads map[string]cipher.AEAD |
| 98 | } |
| 99 | |
| 100 | // New returns a Sealer. The DEK must be exactly 32 bytes. |
| 101 | func New(dek []byte) (*Sealer, error) { |
| 102 | if len(dek) != 32 { |
| 103 | return nil, errors.New("seal: DEK must be 32 bytes") |
| 104 | } |
| 105 | c := make([]byte, 32) |
| 106 | copy(c, dek) |
| 107 | return &Sealer{dek: c, aeads: map[string]cipher.AEAD{}}, nil |
| 108 | } |
| 109 | |
| 110 | // purposeKey derives the AEAD key for purpose via HKDF over the DEK. A |
| 111 | // fixed 32-byte read is always inside HKDF-SHA256's expand limit, so this |
| 112 | // cannot fail today — but the error is still propagated: this is the app's |
| 113 | // only encryption surface, and a silently discarded read here would |
| 114 | // degrade into a short or zero-padded key if the key length ever changed, |
| 115 | // which is the kind of bug that leaves ciphertext looking perfectly fine |
| 116 | // while being trivially breakable. |
| 117 | func (s *Sealer) purposeKey(purpose string) ([]byte, error) { |
| 118 | key := make([]byte, 32) |
| 119 | r := hkdf.New(sha256New, s.dek, nil, []byte("oficina/fichas:"+purpose)) |
| 120 | if _, err := io.ReadFull(r, key); err != nil { |
| 121 | return nil, err |
| 122 | } |
| 123 | return key, nil |
| 124 | } |
| 125 | |
| 126 | func (s *Sealer) aeadFor(purpose string) (cipher.AEAD, error) { |
| 127 | s.mu.RLock() |
| 128 | a, ok := s.aeads[purpose] |
| 129 | s.mu.RUnlock() |
| 130 | if ok { |
| 131 | return a, nil |
| 132 | } |
| 133 | a, err := s.deriveAEAD(purpose) |
| 134 | if err != nil { |
| 135 | return nil, err |
| 136 | } |
| 137 | s.mu.Lock() |
| 138 | s.aeads[purpose] = a |
| 139 | s.mu.Unlock() |
| 140 | return a, nil |
| 141 | } |
| 142 | |
| 143 | func (s *Sealer) deriveAEAD(purpose string) (cipher.AEAD, error) { |
| 144 | key, err := s.purposeKey(purpose) |
| 145 | if err != nil { |
| 146 | return nil, err |
| 147 | } |
| 148 | block, err := aes.NewCipher(key) |
| 149 | if err != nil { |
| 150 | return nil, err |
| 151 | } |
| 152 | return cipher.NewGCM(block) |
| 153 | } |
| 154 | |
| 155 | // Seal encrypts plaintext under purpose. The nonce is prepended. |
| 156 | func (s *Sealer) Seal(purpose string, plaintext []byte) ([]byte, error) { |
| 157 | aead, err := s.aeadFor(purpose) |
| 158 | if err != nil { |
| 159 | return nil, err |
| 160 | } |
| 161 | nonce := make([]byte, aead.NonceSize()) |
| 162 | if _, err := rand.Read(nonce); err != nil { |
| 163 | return nil, err |
| 164 | } |
| 165 | return aead.Seal(nonce, nonce, plaintext, nil), nil |
| 166 | } |
| 167 | |
| 168 | // Open decrypts a value sealed under the same purpose. |
| 169 | func (s *Sealer) Open(purpose string, ct []byte) ([]byte, error) { |
| 170 | aead, err := s.aeadFor(purpose) |
| 171 | if err != nil { |
| 172 | return nil, err |
| 173 | } |
| 174 | if len(ct) < aead.NonceSize() { |
| 175 | return nil, errors.New("seal: ciphertext too short") |
| 176 | } |
| 177 | nonce, body := ct[:aead.NonceSize()], ct[aead.NonceSize():] |
| 178 | return aead.Open(nil, nonce, body, nil) |
| 179 | } |
| 180 | |
| 181 | // fingerprint returns a keyed, deterministic identifier for plaintext. |
| 182 | // |
| 183 | // Keyed, never a bare hash. A bare SHA-256 of a value is a confirmation |
| 184 | // oracle: anyone holding the file and a candidate value can hash it, find |
| 185 | // the row, and learn that this team holds that customer. HMAC under a |
| 186 | // purpose key keeps the idempotency and removes the oracle. |
| 187 | func (s *Sealer) fingerprint(purpose string, plaintext []byte) (string, error) { |
| 188 | key, err := s.purposeKey(purpose) |
| 189 | if err != nil { |
| 190 | return "", err |
| 191 | } |
| 192 | m := hmac.New(sha256New, key) |
| 193 | m.Write(plaintext) |
| 194 | return hex.EncodeToString(m.Sum(nil)), nil |
| 195 | } |
| 196 | |
| 197 | // Print returns the equality-only fingerprint for a value of the field |
| 198 | // identified by fieldKey. |
| 199 | // |
| 200 | // **Only ever call this for a field whose Tier is TierPrint**, and only for |
| 201 | // a high-cardinality one. A print over a low-cardinality field (a five-value |
| 202 | // stage) publishes five equality classes that frequency analysis puts in |
| 203 | // order — which is why §4.2 seals `stage` rather than printing it. This |
| 204 | // function cannot enforce that; the field definition does. |
| 205 | func (s *Sealer) Print(fieldKey string, plaintext []byte) (string, error) { |
| 206 | return s.fingerprint(printPurpose(fieldKey), plaintext) |
| 207 | } |
| 208 | |
| 209 | // RefPrint returns the dedupe fingerprint for a reference target. |
| 210 | func (s *Sealer) RefPrint(plaintext []byte) (string, error) { |
| 211 | return s.fingerprint(refPrintPurpose, plaintext) |
| 212 | } |
| 213 | |