| 1 | package kernel |
| 2 | |
| 3 | import ( |
| 4 | "crypto/aes" |
| 5 | "crypto/cipher" |
| 6 | "crypto/hkdf" |
| 7 | "crypto/rand" |
| 8 | "crypto/sha256" |
| 9 | "encoding/base64" |
| 10 | "encoding/json" |
| 11 | "errors" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | // CursorCodec authenticates opaque positions, never copies of resource contents. |
| 16 | // The caller binds the principal, route and filters through scope. |
| 17 | type CursorCodec struct { |
| 18 | Key string |
| 19 | Now func() time.Time |
| 20 | } |
| 21 | |
| 22 | type cursorEnvelope struct { |
| 23 | Position json.RawMessage |
| 24 | ExpiresAt time.Time |
| 25 | } |
| 26 | |
| 27 | func (c CursorCodec) now() time.Time { |
| 28 | if c.Now != nil { |
| 29 | return c.Now() |
| 30 | } |
| 31 | return time.Now() |
| 32 | } |
| 33 | func (c CursorCodec) aead() (cipher.AEAD, error) { |
| 34 | if c.Key == "" { |
| 35 | return nil, errors.New("missing cursor key") |
| 36 | } |
| 37 | key := PurposeKey(c.Key, "person-api-cursor") |
| 38 | block, err := aes.NewCipher(key) |
| 39 | if err != nil { |
| 40 | return nil, err |
| 41 | } |
| 42 | return cipher.NewGCM(block) |
| 43 | } |
| 44 | func (c CursorCodec) Seal(scope string, position any) (string, error) { |
| 45 | a, err := c.aead() |
| 46 | if err != nil { |
| 47 | return "", err |
| 48 | } |
| 49 | raw, err := json.Marshal(position) |
| 50 | if err != nil { |
| 51 | return "", err |
| 52 | } |
| 53 | raw, err = json.Marshal(cursorEnvelope{raw, c.now().UTC().Add(24 * time.Hour)}) |
| 54 | if err != nil { |
| 55 | return "", err |
| 56 | } |
| 57 | nonce := make([]byte, a.NonceSize()) |
| 58 | if _, err = rand.Read(nonce); err != nil { |
| 59 | return "", err |
| 60 | } |
| 61 | return base64.RawURLEncoding.EncodeToString(a.Seal(nonce, nonce, raw, []byte(scope))), nil |
| 62 | } |
| 63 | func (c CursorCodec) Open(scope, token string, position any) error { |
| 64 | a, err := c.aead() |
| 65 | if err != nil { |
| 66 | return err |
| 67 | } |
| 68 | raw, err := base64.RawURLEncoding.Strict().DecodeString(token) |
| 69 | if err != nil || len(raw) < a.NonceSize() || len(raw) > 4096 { |
| 70 | return errors.New("invalid cursor") |
| 71 | } |
| 72 | raw, err = a.Open(nil, raw[:a.NonceSize()], raw[a.NonceSize():], []byte(scope)) |
| 73 | if err != nil { |
| 74 | return err |
| 75 | } |
| 76 | var envelope cursorEnvelope |
| 77 | if err = json.Unmarshal(raw, &envelope); err != nil { |
| 78 | return err |
| 79 | } |
| 80 | if !c.now().Before(envelope.ExpiresAt) { |
| 81 | return errors.New("expired cursor") |
| 82 | } |
| 83 | return json.Unmarshal(envelope.Position, position) |
| 84 | } |
| 85 | |
| 86 | // PurposeKey separates instance secrets by use. SHA-256 permits the fixed 32-byte length. |
| 87 | func PurposeKey(root, purpose string) []byte { |
| 88 | key, _ := hkdf.Key(sha256.New, []byte(root), nil, "equipo.v1/"+purpose, 32) |
| 89 | return key |
| 90 | } |
| 91 | |