Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ Persistence validation happens on isolated snapshots/decoded values before repla

`FileStorage.WithConflictDetection` returns a pointer backend with a baseline SHA-256 content fingerprint and a cancelable per-instance gate. It canonicalizes the parent directory and uses `gofrs/flock` on a persistent `.lock` sidecar for cross-process compare-and-replace serialization. Lock handles close after every operation; the sidecar must remain while instances are active so all writers lock the same inode. A conflict returns expected/actual fingerprints without replacing primary or backup. Load explicitly accepts the current primary baseline, while LoadBackup leaves it unchanged. The primary-replaced callback advances this instance's baseline before attempting backup, preserving retry after a partial Save. These guarantees require cooperating writers at the same canonical regular local file. Noncooperating concurrent editors can race the check/rename, and content hashes do not detect equal-content or reverted changes. Symlink/nonregular primary files are rejected; hard-link aliases and network locks are outside the contract.

`FileStorage.Durable` additionally synchronizes the parent directory after rename. Windows has no directory fsync, so the sync is skipped there rather than failing a save whose primary was already replaced. On Windows the rename cannot replace a file that another handle holds open without delete sharing, which antivirus and indexer scans, sync clients and plain readers such as another process's Load do; Save retries access-denied, sharing-violation and lock-violation failures with a jittered backoff for up to about 2 s per replaced file, stops early when its context ends, and otherwise returns the failure with the previous file intact. The limit is per file, not per Save: the primary, the `.bak` with `Backup`, and the journal and commit marker with `Journal` each get their own, as does Load's journal recovery, so one Save can wait several times as long and only the context bounds the total. A synchronous `AutoSave` or `AutoSaveWithErrors` runs that wait on the goroutine that updated the store; `AutoSaveAsync` keeps it off. Windows honours only the owner-write bit of `FileStorage.Perm`, as the read-only attribute; MoveFileEx will not replace a read-only file, so Save clears the attribute on the file it replaces, matching rename on other systems, and restores it if the replacement fails. `AESGCMCodec` wraps any inner codec with authenticated AES-GCM encryption, stores only a key ID/nonce/ciphertext envelope, and supports rotation through a `KeyProvider`; keychain access remains application-owned.
`FileStorage.Durable` additionally synchronizes the parent directory after rename. Windows has no directory fsync, so the sync is skipped there rather than failing a save whose primary was already replaced. On Windows the rename cannot replace a file that another handle holds open without delete sharing, which antivirus and indexer scans, sync clients and plain readers such as another process's Load do; Save retries access-denied, sharing-violation and lock-violation failures with a jittered backoff for up to about 2 s per replaced file, stops early when its context ends, and otherwise returns the failure with the previous file intact. The limit is per file, not per Save: the primary, the `.bak` with `Backup`, and the journal and commit marker with `Journal` each get their own, as does Load's journal recovery, so one Save can wait several times as long and only the context bounds the total. A synchronous `AutoSave` or `AutoSaveWithErrors` runs that wait on the goroutine that updated the store; `AutoSaveAsync` keeps it off. Windows honours only the owner-write bit of `FileStorage.Perm`, as the read-only attribute; MoveFileEx will not replace a read-only file, so Save clears the attribute on the file it replaces, matching rename on other systems, and restores it if the replacement fails. `AESGCMCodec` wraps any inner codec with authenticated AES-GCM encryption, stores only a key ID/nonce/ciphertext envelope, and supports rotation through a `KeyProvider`; keychain access remains application-owned. Without `AESGCMCodec.AssociatedData` a ciphertext is bound only to its key, so when two stores share a key, a file of one copied over the other's decodes as valid state for it. Setting `AssociatedData` to the store's identity authenticates that value with the ciphertext under every key, current or historical, without storing it: reading with a different value, or with none, fails like tampered data, which `LoadWithRecovery` treats as a damaged candidate. The empty value seals without associated data, byte for byte the format written before the field existed, so existing files keep loading. Reads and writes must use the same value for the whole lifetime of the data, so a stable logical name such as the application and store name (for example `com.example.app/settings`) is the recommended identity. A file path qualifies only if it never changes: an absolute path changes when the data directory or home folder is moved or renamed, the files are restored onto another machine, or a relative path is resolved from another working directory, and the primary and its backup then both fail authentication, so `LoadWithRecovery` returns a `RecoveryError` although nothing was tampered with. Adding or changing the value for existing data is a migration: load with a codec carrying the old value, then save with one carrying the new value.

## Value composition, history budgets and progress control

Expand Down
2 changes: 1 addition & 1 deletion docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ Use `Derive`, `DeriveProjection`, `Combine`, `Select`, `SubscribeSelector(With)`

`Track` and `TrackWith` provide undo/redo. `History.Undo`, `Redo`, `CanUndo`, `CanRedo`, `BeginGroup`, `Clear`, `Status`, and `Close` are the supported lifecycle. `Clear` drops both stacks and makes the current value the baseline, for a document replaced by Open, New or Revert; it returns `ErrHistoryGroup` while a group is open, `ErrHistoryBatch` inside an open `Batch` and `ErrClosed` after `Close`.

`NewPersistence(WithOptions)` separates state from bytes. `JSONCodec`, `VersionedJSONCodec`, `AESGCMCodec`, `FileStorage`, and `FileStorage.WithConflictDetection` compose the built-in persistence stack; conflict detection returns a `CheckedFileStorage`. The codecs implement `Codec` through `JSONCodec.Encode` and `Decode`, `VersionedJSONCodec.Encode` and `Decode`, and `AESGCMCodec.Encode` and `Decode`. The storages implement `Storage` through `FileStorage.Load`, `LoadBackup`, and `Save` and `CheckedFileStorage.Load`, `LoadBackup`, and `Save`; `LoadBackup` returns `ErrNoBackup` unless `FileStorage.Backup` is set, and a checked `Save` over content another writer changed since the last `Load` returns a `FileConflictError` matching `ErrFileConflict` and leaves the files untouched. `AESGCMCodec` takes its keys from a `KeyProvider`; `NewMemoryKeyProvider` is an in-memory provider for tests and local applications. `MemoryKeyProvider.Add`, `SetCurrent`, `Current`, and `Get` add a key under an id, make an added id the key for new writes, and read the current key or a key by id; empty or unknown ids and invalid AES keys return `ErrInvalidKey`. Rotate by adding the new key before making it current, and keep the old keys so earlier data stays readable. `Persistence.Load`, `LoadBackup`, `LoadWithRecovery`, and `Save` are explicit operations. `Persistence.AutoSave`, `AutoSaveWithErrors`, and `AutoSaveAsync` have distinct shutdown and error behavior. `AutoSaveAsync` returns an `AsyncPersistence`; `AsyncPersistence.Flush`, `Close`, `Errors`, and `Status` expose durability and shutdown results. Callers that need a durable result must handle `Flush` or `Close` errors.
`NewPersistence(WithOptions)` separates state from bytes. `JSONCodec`, `VersionedJSONCodec`, `AESGCMCodec`, `FileStorage`, and `FileStorage.WithConflictDetection` compose the built-in persistence stack; conflict detection returns a `CheckedFileStorage`. The codecs implement `Codec` through `JSONCodec.Encode` and `Decode`, `VersionedJSONCodec.Encode` and `Decode`, and `AESGCMCodec.Encode` and `Decode`. The storages implement `Storage` through `FileStorage.Load`, `LoadBackup`, and `Save` and `CheckedFileStorage.Load`, `LoadBackup`, and `Save`; `LoadBackup` returns `ErrNoBackup` unless `FileStorage.Backup` is set, and a checked `Save` over content another writer changed since the last `Load` returns a `FileConflictError` matching `ErrFileConflict` and leaves the files untouched. `AESGCMCodec` takes its keys from a `KeyProvider`; `NewMemoryKeyProvider` is an in-memory provider for tests and local applications. `MemoryKeyProvider.Add`, `SetCurrent`, `Current`, and `Get` add a key under an id, make an added id the key for new writes, and read the current key or a key by id; empty or unknown ids and invalid AES keys return `ErrInvalidKey`. Rotate by adding the new key before making it current, and keep the old keys so earlier data stays readable. `AESGCMCodec.AssociatedData` binds ciphertext to a store identity under every key: data opens only with the value it was sealed with, so the value must stay the same for the data's whole lifetime. Prefer a stable logical name such as `com.example.app/settings`; an absolute file path changes when the data directory moves and then leaves the data unreadable until migrated. The empty value keeps the original format, and adding or changing the value for existing data needs a migration that loads with the old value and saves with the new one. `Persistence.Load`, `LoadBackup`, `LoadWithRecovery`, and `Save` are explicit operations. `Persistence.AutoSave`, `AutoSaveWithErrors`, and `AutoSaveAsync` have distinct shutdown and error behavior. `AutoSaveAsync` returns an `AsyncPersistence`; `AsyncPersistence.Flush`, `Close`, `Errors`, and `Status` expose durability and shutdown results. Callers that need a durable result must handle `Flush` or `Close` errors.

## Async actions and ownership

Expand Down
8 changes: 6 additions & 2 deletions internal/core/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ func (p *MemoryKeyProvider) Get(id string) ([]byte, error) {
type AESGCMCodec[T any] struct {
Inner Codec[T]
Keys KeyProvider
// AssociatedData is authenticated with the ciphertext under whichever key seals or opens it, current or historical, but it is neither encrypted nor stored in the envelope: Decode accepts only ciphertext that Encode sealed with the same value. Set it to the identity of the store so that two stores sharing a key cannot load each other's files when one is copied over the other. The value must stay the same for as long as the data exists, so prefer a stable logical name such as the application and store name (for example "com.example.app/settings"). A file path works only if it never changes: an absolute path changes when the data directory or home folder is moved or renamed, the files are restored onto another machine, or a relative path is resolved from another working directory, and the primary and its backup then fail to open like tampered data until they are migrated.
//
// The empty string seals without associated data, the format AESGCMCodec has always written, so existing files keep loading. Reading and writing must use the same value; changing it, including setting it for data saved without one, needs a migration that loads with a codec carrying the old value and saves with one carrying the new value.
AssociatedData string
}

type encryptedEnvelope struct {
Expand Down Expand Up @@ -127,7 +131,7 @@ func (c AESGCMCodec[T]) Encode(value T) ([]byte, error) {
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
envelope := encryptedEnvelope{Algorithm: "AES-GCM", KeyID: keyID, Nonce: base64.RawStdEncoding.EncodeToString(nonce), Ciphertext: base64.RawStdEncoding.EncodeToString(gcm.Seal(nil, nonce, plain, nil))}
envelope := encryptedEnvelope{Algorithm: "AES-GCM", KeyID: keyID, Nonce: base64.RawStdEncoding.EncodeToString(nonce), Ciphertext: base64.RawStdEncoding.EncodeToString(gcm.Seal(nil, nonce, plain, []byte(c.AssociatedData)))}
return json.Marshal(envelope)
}

Expand Down Expand Up @@ -163,7 +167,7 @@ func (c AESGCMCodec[T]) Decode(data []byte) (T, error) {
if err != nil {
return zero, errors.New("nodra: invalid encrypted ciphertext")
}
plain, err := gcm.Open(nil, nonce, ciphertext, nil)
plain, err := gcm.Open(nil, nonce, ciphertext, []byte(c.AssociatedData))
if err != nil {
return zero, err
}
Expand Down
99 changes: 99 additions & 0 deletions internal/core/crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package core

import (
"context"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/json"
"errors"
Expand Down Expand Up @@ -112,3 +114,100 @@ func TestAESGCMCodecRejectsEmptyCurrentKeyID(t *testing.T) {
t.Fatalf("empty key ID error = %v, want ErrInvalidKey", err)
}
}

// TestAESGCMCodecAssociatedDataBindsCiphertext checks that a ciphertext sealed with one AssociatedData opens only with that same value, so two stores sharing a key cannot load each other's files.
func TestAESGCMCodecAssociatedDataBindsCiphertext(t *testing.T) {
keys, err := NewMemoryKeyProvider("v1", []byte("01234567890123456789012345678901"))
requireNoError(t, err)
settings := AESGCMCodec[string]{Inner: JSONCodec[string]{}, Keys: keys, AssociatedData: "app/settings.json"}
data, err := settings.Encode("settings state")
requireNoError(t, err)
if value, err := settings.Decode(data); err != nil || value != "settings state" {
t.Fatalf("round trip with associated data: %q %v", value, err)
}
if strings.Contains(string(data), "app/settings.json") {
t.Fatal("associated data was written into the envelope")
}
session := AESGCMCodec[string]{Inner: JSONCodec[string]{}, Keys: keys, AssociatedData: "app/session.json"}
if value, err := session.Decode(data); err == nil {
t.Fatalf("ciphertext sealed for another associated data decoded as %q", value)
}
plain := AESGCMCodec[string]{Inner: JSONCodec[string]{}, Keys: keys}
if value, err := plain.Decode(data); err == nil {
t.Fatalf("ciphertext sealed with associated data decoded without it as %q", value)
}
unbound, err := plain.Encode("unbound state")
requireNoError(t, err)
if value, err := settings.Decode(unbound); err == nil {
t.Fatalf("ciphertext sealed without associated data decoded with it as %q", value)
}
}

// TestAESGCMCodecEmptyAssociatedDataKeepsFormat loads an envelope written before AssociatedData existed and checks that an empty value still seals with no associated data at all.
func TestAESGCMCodecEmptyAssociatedDataKeepsFormat(t *testing.T) {
key := []byte("01234567890123456789012345678901")
keys, err := NewMemoryKeyProvider("v1", key)
requireNoError(t, err)
codec := AESGCMCodec[string]{Inner: JSONCodec[string]{}, Keys: keys}
// Written by AESGCMCodec before the AssociatedData field was added.
saved := []byte(`{"algorithm":"AES-GCM","keyId":"v1","nonce":"DxFrw0zQIfBC0fFg","ciphertext":"RZHUkJu7e/MwTlUZ6u0PpmZew1AEfkUrLzAW+IrLV9CpAmMA7djIbgCpIpxWDQ"}`)
if value, err := codec.Decode(saved); err != nil || value != "saved before associated data" {
t.Fatalf("pre-existing envelope: %q %v", value, err)
}

data, err := codec.Encode("new state")
requireNoError(t, err)
var envelope encryptedEnvelope
requireNoError(t, json.Unmarshal(data, &envelope))
var fields map[string]json.RawMessage
requireNoError(t, json.Unmarshal(data, &fields))
if len(fields) != 4 {
t.Fatalf("envelope fields = %v, want algorithm, keyId, nonce and ciphertext only", fields)
}
nonce, err := base64.RawStdEncoding.DecodeString(envelope.Nonce)
requireNoError(t, err)
ciphertext, err := base64.RawStdEncoding.DecodeString(envelope.Ciphertext)
requireNoError(t, err)
block, err := aes.NewCipher(key)
requireNoError(t, err)
gcm, err := cipher.NewGCM(block)
requireNoError(t, err)
plain, err := gcm.Open(nil, nonce, ciphertext, nil)
requireNoError(t, err)
if string(plain) != `"new state"` {
t.Fatalf("plaintext = %s", plain)
}
}

// TestAESGCMCodecAssociatedDataWithKeyRotation checks that AssociatedData applies to every key of the provider: data sealed before and after a rotation opens only with the same value.
func TestAESGCMCodecAssociatedDataWithKeyRotation(t *testing.T) {
keys, err := NewMemoryKeyProvider("v1", []byte("01234567890123456789012345678901"))
requireNoError(t, err)
codec := AESGCMCodec[string]{Inner: JSONCodec[string]{}, Keys: keys, AssociatedData: "app/settings.json"}
old, err := codec.Encode("old state")
requireNoError(t, err)
requireNoError(t, keys.Add("v2", []byte("abcdefghijklmnopqrstuvwxyz123456")))
requireNoError(t, keys.SetCurrent("v2"))
rotated, err := codec.Encode("new state")
requireNoError(t, err)
var envelope encryptedEnvelope
requireNoError(t, json.Unmarshal(rotated, &envelope))
if envelope.KeyID != "v2" {
t.Fatalf("rotated key ID = %q, want v2", envelope.KeyID)
}
if value, err := codec.Decode(old); err != nil || value != "old state" {
t.Fatalf("old key decode: %q %v", value, err)
}
if value, err := codec.Decode(rotated); err != nil || value != "new state" {
t.Fatalf("new key decode: %q %v", value, err)
}
other := AESGCMCodec[string]{Inner: JSONCodec[string]{}, Keys: keys, AssociatedData: "app/session.json"}
for name, data := range map[string][]byte{"old key": old, "new key": rotated} {
if value, err := other.Decode(data); err == nil {
t.Fatalf("%s: ciphertext decoded with other associated data as %q", name, value)
}
if value, err := (AESGCMCodec[string]{Inner: JSONCodec[string]{}, Keys: keys}).Decode(data); err == nil {
t.Fatalf("%s: ciphertext decoded without associated data as %q", name, value)
}
}
}
34 changes: 34 additions & 0 deletions public_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package nodra_test
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"testing/synctest"
Expand Down Expand Up @@ -127,6 +128,39 @@ func TestRootPersistenceAndAsyncActionContracts(t *testing.T) {
}
}

// TestRootAESGCMCodecAssociatedDataRejectsSwappedFile shares one key between two stores and checks that, with each store's stable logical name as AssociatedData, a file copied from one store over the other fails to load instead of becoming its state.
func TestRootAESGCMCodecAssociatedDataRejectsSwappedFile(t *testing.T) {
ctx := context.Background()
keys, err := nodra.NewMemoryKeyProvider("v1", []byte("01234567890123456789012345678901"))
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
settingsPath, sessionPath := filepath.Join(dir, "settings.enc"), filepath.Join(dir, "session.enc")
settings := nodra.New("settings")
defer func() { _ = settings.Close() }()
session := nodra.New("session")
defer func() { _ = session.Close() }()
settingsCodec := nodra.AESGCMCodec[string]{Inner: nodra.JSONCodec[string]{}, Keys: keys, AssociatedData: "com.example.app/settings"}
sessionCodec := nodra.AESGCMCodec[string]{Inner: nodra.JSONCodec[string]{}, Keys: keys, AssociatedData: "com.example.app/session"}
if err := nodra.NewPersistence(settings, nodra.FileStorage{Path: settingsPath}, settingsCodec).Save(ctx); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(settingsPath)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(sessionPath, data, 0o600); err != nil {
t.Fatal(err)
}
if err := nodra.NewPersistence(session, nodra.FileStorage{Path: sessionPath}, sessionCodec).Load(ctx); err == nil || session.Get() != "session" {
t.Fatalf("swapped file: err=%v value=%q, want an error and the session state kept", err, session.Get())
}
if err := nodra.NewPersistence(session, nodra.FileStorage{Path: settingsPath}, settingsCodec).Load(ctx); err != nil || session.Get() != "settings" {
t.Fatalf("matching associated data: err=%v value=%q", err, session.Get())
}
}

func TestRootAsyncPersistenceMaxWait(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
ctx := context.Background()
Expand Down
Loading