{"record":{"id":"d12e1027d10e14d2","repo":"JuliusBrussee/caveman","slug":"kms-decode-envelope-w","errorCode":null,"errorMessage":"kms: decode envelope: %w","messagePattern":"kms: decode envelope: %w","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"shared/platform/kms/kms.go","lineNumber":231,"sourceCode":"\tclient, err := FromPayloadEnvironment()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client.Decrypt(ctx, blob)\n}\n\n// Decrypt unwraps versioned KMS envelope. Metadata can choose only validated\n// key identity under configured provider; it can never choose host or token.\nfunc (c *Client) Decrypt(ctx context.Context, blob []byte) ([]byte, error) {\n\tif !IsEnvelope(blob) {\n\t\treturn nil, errors.New(\"kms: unknown envelope format\")\n\t}\n\tif len(blob) > maxEnvelopeBytes {\n\t\treturn nil, errors.New(\"kms: envelope exceeds size limit\")\n\t}\n\tvar envelope Envelope\n\tif err := json.Unmarshal(blob[len(prefix):], &envelope); err != nil {\n\t\treturn nil, fmt.Errorf(\"kms: decode envelope: %w\", err)\n\t}\n\tif envelope.Provider != c.provider {\n\t\treturn nil, errors.New(\"kms: envelope provider does not match configured provider\")\n\t}\n\tif err := validateLocation(envelope.Region, envelope.KeyID); err != nil {\n\t\treturn nil, err\n\t}\n\tif envelope.Region != c.region {\n\t\treturn nil, errors.New(\"kms: envelope region is not approved\")\n\t}\n\tif _, ok := c.decryptKeyIDs[envelope.KeyID]; !ok {\n\t\treturn nil, errors.New(\"kms: envelope key ID is not approved\")\n\t}\n\tif strings.TrimSpace(envelope.Ciphertext) == \"\" {\n\t\treturn nil, errors.New(\"kms: envelope ciphertext is empty\")\n\t}\n\tvar response struct {\n\t\tKeyID     string `json:\"key_id\"`","sourceCodeStart":213,"sourceCodeEnd":249,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/27d5a3981a347890211bb1bf2439e5c821a63bc9/shared/platform/kms/kms.go#L213-L249","documentation":"Decrypt first checks IsEnvelope (the 'cave-kms-v1:' prefix) and the 256 KiB envelope size cap, then json.Unmarshals everything after the prefix into Envelope{provider,region,key_id,ciphertext}. This error means the prefix was present but the remaining bytes are not valid Envelope JSON — the envelope is corrupted or was mangled in storage/transit. Provider/region/key checks run only after this decode succeeds.","triggerScenarios":"Envelope string truncated by a column size limit or copy/paste; base64 or URL-encoding applied to part of the blob; hand-crafted string starting with 'cave-kms-v1:' followed by non-JSON; DB or ORM layer escaping/stripping characters inside the JSON; envelope bytes stored as [BLOB] text by a migration tool.","commonSituations":"VARCHAR column too short silently truncating on some databases; secrets passed through templates or logs that strip quotes/newlines; double-encoding when the envelope is embedded in another JSON document as raw text; manual repair attempts on production secret rows.","solutions":["Compare the stored envelope against the original Encrypt output byte-for-byte (length check catches truncation)","Ensure the storage column/type preserves the full string (TEXT/CLOB, no charset rewrites)","Never embed the envelope in another document without re-encoding the whole envelope afterwards","If corruption is confirmed, the ciphertext is unrecoverable — re-encrypt the plaintext from its source of truth"],"exampleFix":"// before\n// stored envelope was truncated by VARCHAR(255)\nstored := \"cave-kms-v1:{\\\"provider\\\":\\\"scaleway\\\",\\\"region\\\":\\\"fr-par\\\"\" // cut mid-JSON\n\n// after\n// store full envelope in TEXT column\nstored := \"cave-kms-v1:{\\\"provider\\\":\\\"scaleway\\\",\\\"region\\\":\\\"fr-par\\\",\\\"key_id\\\":\\\"...\\\",\\\"ciphertext\\\":\\\"...\\\"}\"","handlingStrategy":"validation","validationCode":"func envelopeIntact(blob []byte) bool {\n\tif !kms.IsEnvelope(blob) { return false }\n\tvar e kms.Envelope\n\treturn json.Unmarshal(blob[len(\"cave-kms-v1:\"):], &e) == nil &&\n\t\te.Provider != \"\" && e.Ciphertext != \"\"\n}","typeGuard":"func isValidEnvelope(blob []byte) bool {\n\treturn kms.IsEnvelope(blob) && json.Valid(blob[len(\"cave-kms-v1:\"):])\n}","tryCatchPattern":"if _, err := client.Decrypt(ctx, blob); err != nil { if strings.Contains(err.Error(), \"decode envelope\") { /* quarantine row; do not retry; re-encrypt from source of truth */ } }","preventionTips":["Store envelopes in TEXT/CLOB columns sized for growth; verify byte length after write","Round-trip check (Encrypt then Decrypt) before persisting in a new storage backend","Never pass envelopes through templates, logs, or manual edits"],"tags":["go","kms","envelope","json","corruption"],"backgroundTag":null,"analyzedSha":"27d5a3981a347890211bb1bf2439e5c821a63bc9","analyzedAt":"2026-08-15T09:26:11.751Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}