Merge concurrent saves on the server, with vaults created from the web
Why: the point of a sync server is that two people can work at once. Picking a winner was all this one could do while it could not read a vault. What, end to end: - A vault is created at /web or with `keeporg vault -create`: the server builds an empty KDBX 4 file, encrypts it with the password from the form, and stores it as version 1. An existing database can adopt a stored key with `keeporg db -id <id> -store-password`, which is verified against the stored file before it is accepted. - A stale push to a `merge` vault is no longer refused. The server opens the stored version and the pushed one in memory, folds them together, and stores the re-encrypted result. Clients push as usual and pull what comes back. Any failure answers 409 merge_failed and the client keeps its copy aside, so a failed merge still loses nothing. - At rest: vault contents stay KDBX-encrypted as always. A merge vault's password is kept AES-256-GCM-wrapped under a master key that lives outside the data directory, bound to the vault id, never returned by the API. A stolen data directory is ciphertext; a stolen data directory plus the master key is not. The server runs without a master key and simply refuses to create or merge vaults. This moves the server inside the trust boundary for vaults it can merge, which is inherent to merging and is stated plainly in the README, the handover notes and the web form itself. Key-less strategies are unchanged and remain the default for a database created without a password. Proved: two clients editing the same version are merged rather than refused, the newer edit of one entry wins, a merge failure leaves the stored vault untouched, `merge` is refused without a stored key, the wrapped key never appears in state.json or the API, and the web interface rejects a form without its CSRF token, withholds its cookie over plain http, and only offers groups the user administers. Checked by hand against the real thing: a vault created in a browser, edited by keepassxc-cli on two sides from the same version, merged by the server, and both entries read back out with keepassxc-cli. make check, make test-race, android lint and both .deb builds are clean.
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"cc.tiredsysadmin.keeporg/internal/blob"
|
||||
"cc.tiredsysadmin.keeporg/internal/kdbx"
|
||||
"cc.tiredsysadmin.keeporg/internal/store"
|
||||
)
|
||||
|
||||
// mergePush resolves a stale push by decrypting both copies in memory,
|
||||
// folding them together and storing the result as a new version. Nothing is
|
||||
// written to disk in the clear: the plaintext exists only as these two
|
||||
// kdbx.Database values, and what is stored is an encrypted KDBX file again.
|
||||
//
|
||||
// Any failure answers with a conflict instead, so the client falls back to
|
||||
// keeping its copy aside rather than losing an edit.
|
||||
func (s *Server) mergePush(w http.ResponseWriter, u *store.User, id string, basedOn int64, incoming []byte) {
|
||||
var (
|
||||
wrapped string
|
||||
current int64
|
||||
name string
|
||||
)
|
||||
s.st.Read(func(st *store.State) {
|
||||
if d := st.Databases[id]; d != nil {
|
||||
wrapped, current, name = d.WrappedKey, d.Version, d.Name
|
||||
}
|
||||
})
|
||||
|
||||
result, merged, err := s.mergeInMemory(id, wrapped, current, incoming)
|
||||
if err != nil {
|
||||
s.log.Printf("merge %s (%s): %v", name, id, err)
|
||||
w.Header().Set("ETag", etag(current))
|
||||
w.Header().Set("X-KeepOrg-Strategy", string(store.StrategyMerge))
|
||||
writeJSON(w, http.StatusConflict, map[string]any{
|
||||
"code": "merge_failed", "error": err.Error(),
|
||||
"current_version": current, "merge_strategy": store.StrategyMerge,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
sum := blob.SHA256(merged)
|
||||
var (
|
||||
next int64
|
||||
watchers []string
|
||||
stale bool
|
||||
)
|
||||
if err := s.st.Update(func(st *store.State) error {
|
||||
d := st.Databases[id]
|
||||
if d == nil {
|
||||
return errors.New("no such database")
|
||||
}
|
||||
if d.Version != current {
|
||||
// Someone else landed a version while this merge was running.
|
||||
stale = true
|
||||
return nil
|
||||
}
|
||||
next = d.Version + 1
|
||||
if err := s.blobs.Put(id, next, merged); err != nil {
|
||||
return err
|
||||
}
|
||||
d.Version, d.SHA256, d.Size = next, sum, int64(len(merged))
|
||||
d.UpdatedAt, d.UpdatedBy = time.Now(), u.Username
|
||||
watchers = st.Watchers(id)
|
||||
return nil
|
||||
}); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
if stale {
|
||||
// Ask the client to come back with the newer base; its next attempt
|
||||
// merges against what just landed.
|
||||
w.Header().Set("ETag", etag(current))
|
||||
w.Header().Set("X-KeepOrg-Strategy", string(store.StrategyMerge))
|
||||
writeJSON(w, http.StatusConflict, map[string]any{
|
||||
"code": "conflict", "error": "another merge landed first, retry",
|
||||
"current_version": current, "merge_strategy": store.StrategyMerge,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
_ = s.blobs.Prune(id)
|
||||
s.log.Printf("merged %s into version %d for %s: %s", name, next, u.Username, result)
|
||||
s.hub.Publish(watchers, Event{Type: EventUpdated, DatabaseID: id, Name: name,
|
||||
Version: next, SHA256: sum, By: u.Username})
|
||||
|
||||
w.Header().Set("ETag", etag(next))
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"version": next, "sha256": sum, "unchanged": false,
|
||||
"merged": true, "merge_summary": result.String(), "based_on": basedOn,
|
||||
})
|
||||
}
|
||||
|
||||
// mergeInMemory does the cryptography and the merge. It is separated so the
|
||||
// handler holds no plaintext longer than it must.
|
||||
func (s *Server) mergeInMemory(id, wrapped string, current int64, incoming []byte) (
|
||||
kdbx.MergeResult, []byte, error) {
|
||||
var empty kdbx.MergeResult
|
||||
password, err := s.vaultPassword(id, wrapped)
|
||||
if err != nil {
|
||||
return empty, nil, err
|
||||
}
|
||||
if current == 0 {
|
||||
return empty, nil, errors.New("this vault has no stored version to merge with")
|
||||
}
|
||||
stored, err := s.blobs.Get(id, current)
|
||||
if err != nil {
|
||||
return empty, nil, fmt.Errorf("reading version %d: %w", current, err)
|
||||
}
|
||||
target, err := kdbx.Open(stored, password)
|
||||
if err != nil {
|
||||
return empty, nil, fmt.Errorf("opening the stored vault: %w", err)
|
||||
}
|
||||
source, err := kdbx.Open(incoming, password)
|
||||
if err != nil {
|
||||
// Most often this means the vault's own password was changed by a
|
||||
// client; the server's stored key is then out of date.
|
||||
return empty, nil, fmt.Errorf("opening the pushed vault: %w", err)
|
||||
}
|
||||
result, err := kdbx.Merge(target, source)
|
||||
if err != nil {
|
||||
return empty, nil, err
|
||||
}
|
||||
out, err := target.Marshal(password)
|
||||
if err != nil {
|
||||
return empty, nil, fmt.Errorf("re-encrypting the merged vault: %w", err)
|
||||
}
|
||||
return result, out, nil
|
||||
}
|
||||
Reference in New Issue
Block a user