davsync: scope provider and library credentials during partial sync (#744)
* davsync: scope provider and library credentials during partial sync * davsync: a sync writes which part carries its credentials, and no blank clears one yetone's review of the first cut found two losses the per-part markers caused, and both are fixed by making the markers say exactly which part they belong to: 1. A keyed computer's library-only upload cleared a keyless computer's private MCP token. The blanks in the uploader's library are redactions it downloaded and never held a value for, not clears it made; take now keeps the server's value for an empty secret whatever the policy is, so only a server taken out here is gone. The test that had the loss as its expected now expects the token kept. 2. Mixed versions dropped the remote's provider keys. A keyed upload didn't write the whole-bundle Keys bit, and an older keyless magpie, which reads no per-part marker, uploaded its own providers over the server's with nothing to keep. take sets Keys for the providers' again. The per-part markers are three-state now: a whole collect and a magpie before them write none, and the whole-bundle bit says it then; a sync writes one for every part it merges — true when the upload carried that part's credentials, false when it didn't — and that bit, not Keys, is what a reader goes by. That is what keeps 1 and 2 apart: the providers' whole-bundle bit is set for older readers, while the settings' and the library's own false is what tells a new reader they came without keys and their local values stay. take marks its merged bundle as a sync one (BundleVersion), so a sync's readers never fall back to Keys for a part it wrote. The two regression tests of the first cut that encoded the losses as expected are updated: library/clear keeps the server's secret, and the keyed providers upload writes the whole-bundle bit while leaving the other parts' contents alone. A remote that main already flipped to Keys=true over redacted settings or library isn't repaired by this: the fix keeps new syncs from flipping it, and a keyed computer syncing those parts repairs them by writing them whole. Validation on Windows: go test ./internal/... under a temp HOME passes whole; the davsync, backup, access and settings packages pass with -race; stashing the change fails TestTakeScopedPartCredentials (8 cases), the scoped-sync tests that cover both losses, and the balance-token and restore-scope tests that read the markers. go vet ./internal/... and the darwin, GOOS=linux and GOOS=windows builds pass. * davsync: preserve local secrets when applying partial uploads
This commit is contained in:
+44
-12
@@ -65,7 +65,7 @@ type Bundle struct {
|
||||
Version int `json:"version"`
|
||||
Created time.Time `json:"created"`
|
||||
App string `json:"app,omitempty"` // the magpie that made it
|
||||
Keys bool `json:"keys"` // whether credentials are included
|
||||
Keys bool `json:"keys"` // whole-backup credential policy
|
||||
Providers []provider.Provider `json:"providers"`
|
||||
Icons map[string][]byte `json:"icons,omitempty"` // pictures picked for providers, by file name
|
||||
Groups []provider.Group `json:"groups,omitempty"` // the user's model groups
|
||||
@@ -83,9 +83,11 @@ type Bundle struct {
|
||||
// GroupOrder is the order the user put the routing groups in (#779),
|
||||
// by id; none from a magpie before it, or when never arranged.
|
||||
GroupOrder []string `json:"groupOrder,omitempty"`
|
||||
// SettingsKeys lets sync carry settings credentials without changing the
|
||||
// other parts' Keys policy; absent from older backups and whole collects.
|
||||
SettingsKeys bool `json:"settingsKeys,omitempty"`
|
||||
// Sync can carry one part's credentials without changing the others'
|
||||
// Keys policy; these are absent from older backups and whole collects.
|
||||
ProvidersKeys *bool `json:"providersKeys,omitempty"`
|
||||
SettingsKeys *bool `json:"settingsKeys,omitempty"`
|
||||
LibraryKeys *bool `json:"libraryKeys,omitempty"`
|
||||
}
|
||||
|
||||
type envelope struct {
|
||||
@@ -107,6 +109,35 @@ var ErrPassphrase = errors.New("wrong passphrase, or the file was changed")
|
||||
// the damaged one from this computer rather than fail on it forever.
|
||||
var ErrCorrupt = errors.New("not a magpie backup")
|
||||
|
||||
// BundleVersion is the bundle's structure: 2 carries the per-part
|
||||
// credential markers (ProvidersKeys, SettingsKeys, LibraryKeys) as their
|
||||
// own three-state flags; 1 and before had the whole-bundle Keys alone.
|
||||
const BundleVersion = 2
|
||||
|
||||
// Flag is a per-part credential marker as a bundle field takes one: the
|
||||
// part's own, written when a sync merged it. Absent (nil) is a whole
|
||||
// collect's or an older magpie's.
|
||||
func Flag(keys bool) *bool { return &keys }
|
||||
|
||||
// scopedKeys is whether a part's credentials are in the bundle: the part's
|
||||
// own marker when the bundle carries one — a sync writes it for every part
|
||||
// it merges — and the whole-bundle bit for a whole collect or an older
|
||||
// file, which have no per-part ones. An older writer can also drop the markers
|
||||
// from a v2 file, so a version number alone never implies a credential scope.
|
||||
func (b Bundle) scopedKeys(part string) bool {
|
||||
var own *bool
|
||||
switch part {
|
||||
case "settings":
|
||||
own = b.SettingsKeys
|
||||
case "library":
|
||||
own = b.LibraryKeys
|
||||
}
|
||||
if own != nil {
|
||||
return *own
|
||||
}
|
||||
return b.Keys
|
||||
}
|
||||
|
||||
// Collect gathers the bundle; without keys, providers carry none, nor any
|
||||
// header that looks like one, and the library's servers no environment
|
||||
// variable or header that looks like one (their names stay).
|
||||
@@ -367,7 +398,7 @@ func Restore(b Bundle, parts Parts) (Result, error) {
|
||||
}
|
||||
}
|
||||
if parts.Settings && (b.Settings != nil || b.GatewayKeys != nil) {
|
||||
keys := b.Keys || b.SettingsKeys
|
||||
keys := b.scopedKeys("settings")
|
||||
// the window's size, the proxy, the menu bar's usage are this machine's own
|
||||
cur := settings.Load()
|
||||
s := cur
|
||||
@@ -442,14 +473,15 @@ func Restore(b Bundle, parts Parts) (Result, error) {
|
||||
}
|
||||
}
|
||||
if parts.Library && b.Library != nil {
|
||||
lib := b.Library
|
||||
if !b.Keys { // the servers' keys kept here stay
|
||||
have, err := library.Collect()
|
||||
if err != nil {
|
||||
return r, err
|
||||
}
|
||||
lib = lib.WithSecrets(have, Secret)
|
||||
// Even a keyed uploader can carry a redaction it downloaded and never
|
||||
// held a value for. Fill blanks from this computer at apply time: the
|
||||
// remote may never have held its private token. Nonempty replacements
|
||||
// and removed entries still take effect.
|
||||
have, err := library.Collect()
|
||||
if err != nil {
|
||||
return r, err
|
||||
}
|
||||
lib := b.Library.WithSecrets(have, Secret)
|
||||
res, err := library.Put(lib)
|
||||
if err != nil {
|
||||
return r, fmt.Errorf("the library: %w", err)
|
||||
|
||||
@@ -12,24 +12,6 @@ import (
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// The serialized field lets these regressions run against the older Bundle
|
||||
// too: ignoring the new settings-only credential scope must fail at restore.
|
||||
func withSettingsKeys(t *testing.T, b Bundle, keys bool) Bundle {
|
||||
t.Helper()
|
||||
plain, err := json.Marshal(struct {
|
||||
Bundle
|
||||
SettingsKeys bool `json:"settingsKeys,omitempty"`
|
||||
}{b, keys})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out Bundle
|
||||
if err := json.Unmarshal(plain, &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestCollectSettingsKeysCompatibility(t *testing.T) {
|
||||
home(t)
|
||||
appdir.UseExecutable("")
|
||||
@@ -49,8 +31,13 @@ func TestCollectSettingsKeysCompatibility(t *testing.T) {
|
||||
if err := json.Unmarshal(plain, &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := fields["settingsKeys"]; ok || b.Keys != keys {
|
||||
t.Error("a whole backup changed its existing credential policy or added a settings-only marker")
|
||||
for _, field := range []string{"providersKeys", "settingsKeys", "libraryKeys"} {
|
||||
if _, ok := fields[field]; ok {
|
||||
t.Errorf("a whole backup added a sync-only %s marker", field)
|
||||
}
|
||||
}
|
||||
if b.Keys != keys {
|
||||
t.Error("a whole backup changed its existing credential policy")
|
||||
}
|
||||
if !keys && (b.GatewayKeys != nil || b.Settings.LANKey != "" || b.Settings.LANKeyID != "") {
|
||||
t.Error("a keyless backup included settings credentials")
|
||||
@@ -96,10 +83,14 @@ func TestRestoreSettingsKeysScope(t *testing.T) {
|
||||
OTel: settings.OTel{Endpoint: "https://remote.example.com", Headers: map[string]string{"Authorization": "fixture-remote-otel"}}}
|
||||
keys := []access.Key{{ID: incoming.LANKeyID, Name: "Remote", LAN: true, Secret: incoming.LANKey},
|
||||
{ID: "client", Name: "Client", Secret: "fixture-remote-client"}}
|
||||
b := withSettingsKeys(t, Bundle{Version: 1, Settings: &incoming, GatewayKeys: &keys,
|
||||
version := 1
|
||||
if tc.keys {
|
||||
version = BundleVersion // a sync bundle from a keyed uploader carries the markers
|
||||
}
|
||||
b := Bundle{Version: version, SettingsKeys: Flag(tc.keys), Settings: &incoming, GatewayKeys: &keys,
|
||||
Providers: []provider.Provider{{ID: "acme", Name: "Remote", Chat: "https://remote.example.com/v1"}},
|
||||
Library: &library.Bundle{MCP: []*library.Server{{Name: "github", Transport: "stdio", Command: "remote-mcp",
|
||||
Env: map[string]string{"GITHUB_TOKEN": "", "MODE": "remote"}, Agents: []string{}}}}}, tc.keys)
|
||||
Env: map[string]string{"GITHUB_TOKEN": "", "MODE": "remote"}, Agents: []string{}}}}}
|
||||
r, err := Restore(b, tc.parts)
|
||||
if err != nil || r.Settings != tc.parts.Settings || r.Library != tc.parts.Library {
|
||||
t.Fatal("restore did not honor the selected parts", r, err)
|
||||
@@ -158,7 +149,7 @@ func TestRestoreSettingsKeysStore(t *testing.T) {
|
||||
case "legacy":
|
||||
b.Settings = &settings.Settings{Theme: "light", LAN: true, LANKey: "fixture-older-lan", LANKeyID: "old-marker", GitHubToken: "fixture-older-github"}
|
||||
}
|
||||
b = withSettingsKeys(t, b, true)
|
||||
b.SettingsKeys = Flag(true)
|
||||
if _, err := Restore(b, Parts{Settings: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -191,7 +182,7 @@ func TestRestoreSettingsKeysStore(t *testing.T) {
|
||||
func TestRestoreSettingsKeysLegacyLAN(t *testing.T) {
|
||||
home(t)
|
||||
appdir.UseExecutable("")
|
||||
b := withSettingsKeys(t, Bundle{Version: 1, Settings: &settings.Settings{LAN: true, LANKey: "fixture-legacy-lan", LANKeyID: "incomplete-marker"}}, true)
|
||||
b := Bundle{Version: BundleVersion, SettingsKeys: Flag(true), Settings: &settings.Settings{LAN: true, LANKey: "fixture-legacy-lan", LANKeyID: "incomplete-marker"}}
|
||||
if _, err := Restore(b, Parts{Settings: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package backup
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
func TestRestoreLibraryKeysScope(t *testing.T) {
|
||||
for _, policy := range []string{"keyless", "full", "settings", "providers", "library"} {
|
||||
for _, selected := range []bool{false, true} {
|
||||
name := policy + "/excluded"
|
||||
if selected {
|
||||
name = policy + "/selected"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
home(t)
|
||||
appdir.UseExecutable("")
|
||||
cur := settings.Load()
|
||||
cur.GitHubToken = "fixture-local-github"
|
||||
if err := settings.Save(cur); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := library.SaveServer("", library.Server{Name: "github", Transport: "stdio", Command: "fixture-mcp",
|
||||
Env: map[string]string{"GITHUB_TOKEN": "fixture-local-mcp"}, Agents: []string{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := library.SaveServer("", library.Server{Name: "headers", Transport: "http", URL: "https://mcp.example.com",
|
||||
Headers: map[string]string{"Authorization": "fixture-local-header"}, Agents: []string{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b := Bundle{Version: BundleVersion, Keys: policy == "full", Library: &library.Bundle{MCP: []*library.Server{{Name: "github", Transport: "stdio", Command: "changed-mcp",
|
||||
Env: map[string]string{"GITHUB_TOKEN": ""}, Agents: []string{}}, {Name: "headers", Transport: "http", URL: "https://mcp.example.com",
|
||||
Headers: map[string]string{"Authorization": ""}, Agents: []string{}}}}}
|
||||
if policy != "keyless" && policy != "full" {
|
||||
// Read a serialized scoped bundle, as an imported backup would.
|
||||
if err := json.Unmarshal([]byte(`{"`+policy+`Keys":true}`), &b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := Restore(b, Parts{Library: selected}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := library.Collect()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantToken, wantHeader, wantCommand := "fixture-local-mcp", "fixture-local-header", "fixture-mcp"
|
||||
if selected {
|
||||
wantCommand = "changed-mcp"
|
||||
}
|
||||
if got.MCP[0].Command != wantCommand || got.MCP[0].Env["GITHUB_TOKEN"] != wantToken || got.MCP[1].Headers["Authorization"] != wantHeader {
|
||||
t.Errorf("library restoration ignored its selected credential scope: command=%q, token=%q, header=%q", got.MCP[0].Command, got.MCP[0].Env["GITHUB_TOKEN"], got.MCP[1].Headers["Authorization"])
|
||||
}
|
||||
if settings.Load().GitHubToken != cur.GitHubToken {
|
||||
t.Error("restoring the library changed an unselected settings credential")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreLibraryCredentialUpdates(t *testing.T) {
|
||||
for _, scoped := range []bool{false, true} {
|
||||
for _, action := range []string{"replace", "remove-keys", "remove-server"} {
|
||||
policy := "full"
|
||||
if scoped {
|
||||
policy = "library"
|
||||
}
|
||||
t.Run(policy+"/"+action, func(t *testing.T) {
|
||||
home(t)
|
||||
appdir.UseExecutable("")
|
||||
server := library.Server{Name: "github", Transport: "stdio", Command: "fixture-mcp", Agents: []string{},
|
||||
Env: map[string]string{"GITHUB_TOKEN": "fixture-local", "MODE": "local"}}
|
||||
if _, err := library.SaveServer("", server); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
headers := library.Server{Name: "headers", Transport: "http", URL: "https://mcp.example.com", Agents: []string{},
|
||||
Headers: map[string]string{"Authorization": "fixture-local-header", "X-Mode": "local"}}
|
||||
if _, err := library.SaveServer("", headers); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server.Env = map[string]string{"GITHUB_TOKEN": "fixture-new", "MODE": ""}
|
||||
headers.Headers = map[string]string{"Authorization": "fixture-new-header", "X-Mode": ""}
|
||||
b := Bundle{Version: BundleVersion, Keys: !scoped, Library: &library.Bundle{MCP: []*library.Server{&server, &headers}}}
|
||||
if scoped {
|
||||
b.LibraryKeys = Flag(true)
|
||||
}
|
||||
switch action {
|
||||
case "remove-keys":
|
||||
delete(server.Env, "GITHUB_TOKEN")
|
||||
delete(headers.Headers, "Authorization")
|
||||
case "remove-server":
|
||||
b.Library.MCP = nil
|
||||
}
|
||||
if _, err := Restore(b, Parts{Library: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := library.Collect()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if action == "remove-server" {
|
||||
if len(got.MCP) != 0 {
|
||||
t.Fatal("restoring credentials resurrected a removed server")
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(got.MCP) != 2 || got.MCP[0].Env["MODE"] != "" || got.MCP[1].Headers["X-Mode"] != "" {
|
||||
t.Fatal("a non-secret blank was replaced with a local value")
|
||||
}
|
||||
if action == "replace" {
|
||||
if got.MCP[0].Env["GITHUB_TOKEN"] != "fixture-new" || got.MCP[1].Headers["Authorization"] != "fixture-new-header" {
|
||||
t.Fatal("a nonempty incoming credential did not replace the local value")
|
||||
}
|
||||
} else {
|
||||
if _, ok := got.MCP[0].Env["GITHUB_TOKEN"]; ok {
|
||||
t.Error("a removed environment key came back")
|
||||
}
|
||||
if _, ok := got.MCP[1].Headers["Authorization"]; ok {
|
||||
t.Error("a removed header came back")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ func TestTakeBalanceToken(t *testing.T) {
|
||||
if c.serverKeys && !c.incomingKeys {
|
||||
wantKey = server.Key
|
||||
}
|
||||
if got.Key != wantKey || to.Keys != (c.serverKeys || c.incomingKeys) {
|
||||
if got.Key != wantKey || to.Keys != (c.serverKeys || c.incomingKeys) || (to.Keys || (to.ProvidersKeys != nil && *to.ProvidersKeys)) != (c.serverKeys || c.incomingKeys) {
|
||||
t.Fatalf("keys after merge: %+v", to)
|
||||
}
|
||||
if !reflect.DeepEqual(from.Providers, []provider.Provider{incoming}) {
|
||||
|
||||
@@ -614,12 +614,29 @@ func orEmpty[V any](m map[string]V) map[string]V {
|
||||
return m
|
||||
}
|
||||
|
||||
// take puts from's part in to.
|
||||
// take puts from's part in to. The merged bundle is a sync one (BundleVersion):
|
||||
// its per-part markers, not the whole-bundle Keys bit, say which part
|
||||
// carries credentials, so a keyed providers upload no longer tells a reader
|
||||
// the settings and the library came with keys too. If an older writer drops
|
||||
// those markers, readers fall back to Keys even if the version stays 2.
|
||||
func take(to *backup.Bundle, from backup.Bundle, part string) {
|
||||
// Preserve every legacy part's scope before a providers upload changes
|
||||
// Keys for older readers. An untouched nil marker would otherwise inherit
|
||||
// that new value and turn a redaction into a credential-bearing update.
|
||||
if to.ProvidersKeys == nil {
|
||||
to.ProvidersKeys = backup.Flag(to.Keys)
|
||||
}
|
||||
if to.SettingsKeys == nil {
|
||||
to.SettingsKeys = backup.Flag(to.Keys)
|
||||
}
|
||||
if to.LibraryKeys == nil {
|
||||
to.LibraryKeys = backup.Flag(to.Keys)
|
||||
}
|
||||
switch part {
|
||||
case "providers":
|
||||
keys := from.Keys || (from.ProvidersKeys != nil && *from.ProvidersKeys)
|
||||
ps := from.Providers
|
||||
if !from.Keys && to.Keys { // sent without keys: keep the ones the server has
|
||||
if !keys && (to.Keys || (to.ProvidersKeys != nil && *to.ProvidersKeys)) { // sent without keys: keep the ones the server has
|
||||
keys := map[string]provider.Provider{}
|
||||
for _, p := range to.Providers {
|
||||
keys[p.ID] = p
|
||||
@@ -635,7 +652,7 @@ func take(to *backup.Bundle, from backup.Bundle, part string) {
|
||||
}
|
||||
}
|
||||
searches := from.Searches
|
||||
if searches != nil && !from.Keys && to.Keys && to.Searches != nil { // the same for the search APIs
|
||||
if searches != nil && !keys && (to.Keys || (to.ProvidersKeys != nil && *to.ProvidersKeys)) && to.Searches != nil { // the same for the search APIs
|
||||
keys := map[string]string{}
|
||||
for _, a := range *to.Searches {
|
||||
keys[a.Vendor] = a.Key
|
||||
@@ -649,11 +666,12 @@ func take(to *backup.Bundle, from backup.Bundle, part string) {
|
||||
searches = &ss
|
||||
}
|
||||
to.Providers, to.Icons, to.Groups, to.Searches, to.Order, to.GroupOrder = ps, from.Icons, from.Groups, searches, from.Order, from.GroupOrder
|
||||
to.Keys = to.Keys || from.Keys
|
||||
to.ProvidersKeys = backup.Flag(keys || (to.ProvidersKeys != nil && *to.ProvidersKeys))
|
||||
to.Keys = to.Keys || keys // the whole-bundle bit follows it, for a magpie that reads no per-part ones: it keeps the server's keys on its own upload then
|
||||
case "settings":
|
||||
keys := from.Keys || from.SettingsKeys
|
||||
keys := from.Keys || (from.SettingsKeys != nil && *from.SettingsKeys)
|
||||
s := from.Settings
|
||||
if s != nil && !keys && (to.Keys || to.SettingsKeys) && to.Settings != nil {
|
||||
if s != nil && !keys && (to.Keys || (to.SettingsKeys != nil && *to.SettingsKeys)) && to.Settings != nil {
|
||||
// Sent without keys: keep the ones the server has, as for providers.
|
||||
copy := *s
|
||||
copy.LANKey, copy.LANKeyID = to.Settings.LANKey, to.Settings.LANKeyID
|
||||
@@ -670,18 +688,26 @@ func take(to *backup.Bundle, from backup.Bundle, part string) {
|
||||
if keys && from.GatewayKeys != nil {
|
||||
to.GatewayKeys = from.GatewayKeys // an explicit empty store clears it
|
||||
}
|
||||
to.SettingsKeys = to.SettingsKeys || keys
|
||||
to.SettingsKeys = backup.Flag(keys || (to.SettingsKeys != nil && *to.SettingsKeys))
|
||||
case "profiles":
|
||||
to.Profiles = from.Profiles
|
||||
case "agents":
|
||||
to.Agents = from.Agents
|
||||
case "library":
|
||||
keys := from.Keys || (from.LibraryKeys != nil && *from.LibraryKeys)
|
||||
lib := from.Library
|
||||
if lib != nil && !from.Keys && to.Keys { // sent without keys: keep the ones the server has
|
||||
// An empty secret is not a clear: a keyed computer's library holds
|
||||
// "" for a server it synced and never held a token for, and writes
|
||||
// that over the token the keyless computer that set it up has. The
|
||||
// server's value is kept for such an entry whatever the policy; a
|
||||
// server taken out here is gone, as a part's own clearing works.
|
||||
if lib != nil && (to.Keys || (to.LibraryKeys != nil && *to.LibraryKeys)) {
|
||||
lib = lib.WithSecrets(to.Library, backup.Secret)
|
||||
}
|
||||
to.Library = lib
|
||||
to.LibraryKeys = backup.Flag(keys || (to.LibraryKeys != nil && *to.LibraryKeys))
|
||||
}
|
||||
to.Version = backup.BundleVersion // the merged bundle is a sync one, whatever the server's file was
|
||||
}
|
||||
|
||||
// changed is when a part was last changed here, as its files say.
|
||||
|
||||
@@ -273,22 +273,6 @@ func TestGatewayKeysWithLibraryOffSync(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func scopedSettingsBundle(t *testing.T, b backup.Bundle, keys bool) backup.Bundle {
|
||||
t.Helper()
|
||||
plain, err := json.Marshal(struct {
|
||||
backup.Bundle
|
||||
SettingsKeys bool `json:"settingsKeys,omitempty"`
|
||||
}{b, keys})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out backup.Bundle
|
||||
if err := json.Unmarshal(plain, &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestGatewayKeysTakeScopedSettings(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
@@ -320,7 +304,7 @@ func TestGatewayKeysTakeScopedSettings(t *testing.T) {
|
||||
case "key-only":
|
||||
from.Settings = nil
|
||||
}
|
||||
from = scopedSettingsBundle(t, from, tc.scoped)
|
||||
from.SettingsKeys = backup.Flag(tc.scoped)
|
||||
beforeTo, _ := json.Marshal(to)
|
||||
beforeFrom, _ := json.Marshal(from)
|
||||
merged := to
|
||||
@@ -368,8 +352,8 @@ func TestGatewayKeysTakeKeylessOntoScopedSettings(t *testing.T) {
|
||||
t.Run(map[bool]string{false: "different-endpoint", true: "same-endpoint"}[sameEndpoint], func(t *testing.T) {
|
||||
old := settings.Settings{Theme: "dark", LANKey: "fixture-server-lan", LANKeyID: "server-lan", GitHubToken: "fixture-server-github",
|
||||
OTel: settings.OTel{Endpoint: "https://collector.example.com", Headers: map[string]string{"Authorization": "fixture-server-otel"}}}
|
||||
to := scopedSettingsBundle(t, backup.Bundle{Settings: &old,
|
||||
GatewayKeys: &[]access.Key{{ID: "server", Name: "Server", Secret: "fixture-server-gateway"}}}, true)
|
||||
to := backup.Bundle{Version: backup.BundleVersion, SettingsKeys: backup.Flag(true), Settings: &old,
|
||||
GatewayKeys: &[]access.Key{{ID: "server", Name: "Server", Secret: "fixture-server-gateway"}}}
|
||||
next := settings.Settings{Theme: "light", OTel: settings.OTel{Endpoint: "https://other.example.com"}}
|
||||
if sameEndpoint {
|
||||
next.OTel.Endpoint = old.OTel.Endpoint + "/"
|
||||
|
||||
@@ -68,7 +68,7 @@ func TestGatewayKeysTakeSettings(t *testing.T) {
|
||||
if want == nil {
|
||||
want = old // a missing field gives no instruction to replace it
|
||||
}
|
||||
if to.Settings != from.Settings || !reflect.DeepEqual(to.GatewayKeys, want) || to.Keys || !to.SettingsKeys {
|
||||
if to.Settings != from.Settings || !reflect.DeepEqual(to.GatewayKeys, want) || to.Keys || to.SettingsKeys == nil || !*to.SettingsKeys {
|
||||
t.Error("settings did not retain the gateway store and credential flag")
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package davsync
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/backup"
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// The remote never held C's token. A's keyed library upload therefore cannot
|
||||
// recover it at merge time: C must preserve its own secret when applying it.
|
||||
func TestKeyedLibraryUploadPreservesKeylessLocalSecrets(t *testing.T) {
|
||||
f, srv := newFakeS3(t)
|
||||
cfg := f.config(srv)
|
||||
cfg.Keys, cfg.Agents = false, false
|
||||
a, c := newComputer(t), newComputer(t)
|
||||
use := func(computer computer) {
|
||||
t.Helper()
|
||||
computer.use(t)
|
||||
appdir.UseExecutable("")
|
||||
provider.ForgetAccounts()
|
||||
}
|
||||
t.Cleanup(provider.ForgetAccounts)
|
||||
now := func() {
|
||||
t.Helper()
|
||||
if err := Now(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
collect := func() *library.Bundle {
|
||||
t.Helper()
|
||||
b, err := library.Collect()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
remote := func() backup.Bundle {
|
||||
t.Helper()
|
||||
f.mu.Lock()
|
||||
data := slices.Clone(f.objects["team x+y/magpie/magpie.magpie-backup"])
|
||||
f.mu.Unlock()
|
||||
b, err := backup.Open(data, cfg.Passphrase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
use(c)
|
||||
if _, err := library.SaveServer("", library.Server{Name: "github", Transport: "stdio", Command: "fixture-mcp",
|
||||
Env: map[string]string{"GITHUB_TOKEN": "fixture-c-mcp"}, Agents: []string{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Configure(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now()
|
||||
if got := remote(); got.Keys || got.Library.MCP[0].Env["GITHUB_TOKEN"] != "" {
|
||||
t.Fatal("C must start a remote without its private token")
|
||||
}
|
||||
|
||||
use(a)
|
||||
keyed := cfg
|
||||
keyed.Keys = true
|
||||
if err := Configure(keyed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now()
|
||||
if collect().MCP[0].Env["GITHUB_TOKEN"] != "" {
|
||||
t.Fatal("A must receive a redaction, not C's private token")
|
||||
}
|
||||
text := "Instructions edited by A."
|
||||
if _, err := library.SaveInstructions(library.InstructionsChange{Shared: &text}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now()
|
||||
if got := remote(); got.LibraryKeys == nil || !*got.LibraryKeys || got.Library.MCP[0].Env["GITHUB_TOKEN"] != "" {
|
||||
t.Fatal("A's keyed library upload must still contain the redacted token")
|
||||
}
|
||||
|
||||
use(c)
|
||||
now()
|
||||
got := collect()
|
||||
if got.Texts["default"] != text || got.MCP[0].Env["GITHUB_TOKEN"] != "fixture-c-mcp" {
|
||||
t.Fatalf("C must receive A's instructions and keep its own token: text=%q, token=%q", got.Texts["default"], got.MCP[0].Env["GITHUB_TOKEN"])
|
||||
}
|
||||
now()
|
||||
if remote().Library.MCP[0].Env["GITHUB_TOKEN"] != "" {
|
||||
t.Fatal("C's keyless sync uploaded its private token")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package davsync
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/backup"
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// A providers-only upload must not turn the remote's redacted settings and
|
||||
// library into instructions to clear another computer's private credentials.
|
||||
func TestProviderKeysPreserveOtherSecretsSync(t *testing.T) {
|
||||
for _, libraryOff := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("libraryOff=%v", libraryOff), func(t *testing.T) {
|
||||
f, srv := newFakeS3(t)
|
||||
cfg := f.config(srv)
|
||||
cfg.Keys, cfg.Agents = false, false
|
||||
a, b, c := newComputer(t), newComputer(t), newComputer(t)
|
||||
use := func(c computer) {
|
||||
t.Helper()
|
||||
c.use(t)
|
||||
appdir.UseExecutable("")
|
||||
provider.ForgetAccounts()
|
||||
}
|
||||
t.Cleanup(provider.ForgetAccounts)
|
||||
now := func() {
|
||||
t.Helper()
|
||||
if err := Now(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
remote := func() backup.Bundle {
|
||||
t.Helper()
|
||||
f.mu.Lock()
|
||||
data := slices.Clone(f.objects["team x+y/magpie/magpie.magpie-backup"])
|
||||
f.mu.Unlock()
|
||||
got, err := backup.Open(data, cfg.Passphrase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
puts := func() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
n := 0
|
||||
for _, request := range f.log {
|
||||
if strings.HasPrefix(request, "PUT") {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
private := func(name string) {
|
||||
t.Helper()
|
||||
s := settings.Load()
|
||||
s.Theme, s.GitHubToken = "dark", "fixture-"+name+"-github"
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := library.SaveServer("", library.Server{Name: "github", Transport: "stdio", Command: "fixture-mcp",
|
||||
Env: map[string]string{"GITHUB_TOKEN": "fixture-" + name + "-mcp"}, Agents: []string{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
say := func(text string) {
|
||||
t.Helper()
|
||||
if _, err := library.SaveInstructions(library.InstructionsChange{Shared: &text}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
use(a)
|
||||
private("a")
|
||||
say("Initial shared instructions.")
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "https://relay.example.com/v1", Key: "fixture-a-provider"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Configure(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now()
|
||||
initial := remote()
|
||||
if initial.Keys || initial.Library == nil || len(initial.Library.MCP) != 1 || initial.Library.MCP[0].Env["GITHUB_TOKEN"] != "" || initial.Settings.GitHubToken != "" {
|
||||
t.Fatal("the initial remote was not keyless")
|
||||
}
|
||||
|
||||
use(b)
|
||||
private("b")
|
||||
say("Private instructions.")
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Local", Chat: "https://relay.example.com/v1", Key: "fixture-b-provider"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keyed := cfg
|
||||
keyed.Keys = true
|
||||
if libraryOff {
|
||||
off := false
|
||||
keyed.Library = &off
|
||||
}
|
||||
if err := Configure(keyed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now()
|
||||
before := puts()
|
||||
now()
|
||||
if puts() != before || settings.Load().GitHubToken != "fixture-b-github" {
|
||||
t.Fatal("joining the keyless remote uploaded a change or erased a local credential")
|
||||
}
|
||||
p, err := provider.Find("relay")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.Name = "Renamed by B"
|
||||
if err := provider.Save(*p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now()
|
||||
got := remote()
|
||||
if puts() != before+1 || got.Providers[0].Name != p.Name || got.Providers[0].Key != "fixture-b-provider" {
|
||||
t.Fatal("the providers-only change was not uploaded once")
|
||||
}
|
||||
t.Logf("after providers-only upload: Keys=%v, remote MCP token present=%v, remote GitHub token present=%v", got.Keys,
|
||||
got.Library.MCP[0].Env["GITHUB_TOKEN"] != "", got.Settings.GitHubToken != "")
|
||||
if !got.Keys || !reflect.DeepEqual(got.Library, initial.Library) || !reflect.DeepEqual(got.Settings, initial.Settings) {
|
||||
t.Error("a keyed providers upload left the whole-bundle bit an older reader needs, or changed unselected parts")
|
||||
}
|
||||
// Join immediately after that upload, before any settings upload
|
||||
// has written an explicit settingsKeys marker. A different theme
|
||||
// ensures the redacted settings are actually applied on this peer.
|
||||
use(newComputer(t))
|
||||
private("d")
|
||||
different := settings.Load()
|
||||
different.Theme = "light"
|
||||
if err := settings.Save(different); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Configure(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now()
|
||||
if got := settings.Load(); got.Theme != "dark" || got.GitHubToken != "fixture-d-github" {
|
||||
t.Error("joining immediately after a providers-only upload cleared D's private GitHub token")
|
||||
}
|
||||
|
||||
use(a)
|
||||
now()
|
||||
say("Updated shared instructions.")
|
||||
s := settings.Load()
|
||||
s.Theme = "light"
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now()
|
||||
if puts() != before+2 || remote().Providers[0].Key != "fixture-b-provider" {
|
||||
t.Fatal("a keyless upload lost the server's provider key or did not upload the other parts once")
|
||||
}
|
||||
use(b)
|
||||
now()
|
||||
if got := settings.Load(); got.Theme != "light" || got.GitHubToken != "fixture-b-github" {
|
||||
t.Error("a later settings download cleared B's private GitHub token")
|
||||
}
|
||||
lib, err := library.Collect()
|
||||
if err != nil || lib.MCP[0].Env["GITHUB_TOKEN"] != "fixture-b-mcp" {
|
||||
t.Error("a later library download cleared B's private MCP token", err)
|
||||
}
|
||||
wantText := "Updated shared instructions."
|
||||
if libraryOff {
|
||||
wantText = "Private instructions."
|
||||
}
|
||||
if lib.Texts["default"] != wantText {
|
||||
t.Error("the library did not honor the selected sync parts")
|
||||
}
|
||||
|
||||
use(c)
|
||||
private("c")
|
||||
if err := Configure(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now()
|
||||
lib, err = library.Collect()
|
||||
if err != nil || lib.Texts["default"] != "Updated shared instructions." || lib.MCP[0].Env["GITHUB_TOKEN"] != "fixture-c-mcp" {
|
||||
t.Error("joining after the providers upload cleared C's private MCP token", err)
|
||||
}
|
||||
if got := settings.Load(); got.Theme != "light" || got.GitHubToken != "fixture-c-github" {
|
||||
t.Error("joining after the providers upload cleared C's private GitHub token")
|
||||
}
|
||||
now()
|
||||
if puts() != before+2 {
|
||||
t.Error("a downloaded or unchanged part was uploaded again")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTakeScopedPartCredentials(t *testing.T) {
|
||||
for _, part := range []string{"providers", "library"} {
|
||||
for _, server := range []string{"keyless", "full", "scoped"} {
|
||||
for _, source := range []string{"keyless", "full", "scoped", "clear"} {
|
||||
t.Run(part+"/"+server+"/"+source, func(t *testing.T) {
|
||||
makeBundle := func(policy, value string) backup.Bundle {
|
||||
b := backup.Bundle{Version: backup.BundleVersion, Keys: policy == "full", SettingsKeys: backup.Flag(true),
|
||||
Settings: &settings.Settings{GitHubToken: value},
|
||||
Providers: []provider.Provider{{ID: "relay", Name: value, Key: value, BalanceToken: value}},
|
||||
Searches: &[]provider.SearchAPI{{Vendor: "tavily", Key: value}},
|
||||
Library: &library.Bundle{MCP: []*library.Server{{Name: "github", Transport: "stdio", Command: "fixture-mcp",
|
||||
Env: map[string]string{"GITHUB_TOKEN": value}, Headers: map[string]string{"Authorization": value}}}}}
|
||||
if policy == "scoped" || policy == "clear" {
|
||||
// Use the wire field so these tests also run on an older reader.
|
||||
if err := json.Unmarshal(fmt.Appendf(nil, `{"%sKeys":true}`, part), &b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
old, next := "fixture-server", "fixture-source"
|
||||
if server == "keyless" {
|
||||
old = ""
|
||||
}
|
||||
if source == "keyless" || source == "clear" {
|
||||
next = ""
|
||||
}
|
||||
to, from := makeBundle(server, old), makeBundle(source, next)
|
||||
beforeTo, _ := json.Marshal(to)
|
||||
beforeFrom, _ := json.Marshal(from)
|
||||
merged := to
|
||||
take(&merged, from, part)
|
||||
if merged.SettingsKeys != to.SettingsKeys || merged.Settings != to.Settings {
|
||||
t.Error("taking one part changed another part's credential policy or settings")
|
||||
}
|
||||
if part == "providers" {
|
||||
// the whole-bundle bit follows the providers' own when
|
||||
// this upload carried them, so a magpie that reads no
|
||||
// per-part ones still keeps the server's keys when it
|
||||
// uploads after a keyed one
|
||||
if (from.Keys || (from.ProvidersKeys != nil && *from.ProvidersKeys)) && (merged.ProvidersKeys != nil && *merged.ProvidersKeys) && !merged.Keys {
|
||||
t.Error("the providers carry their scope without the whole-bundle bit, which an older reader would lose the keys to")
|
||||
}
|
||||
} else if merged.Keys != to.Keys {
|
||||
t.Error("taking the library changed the providers' or the whole bundle's credential policy")
|
||||
}
|
||||
want := next
|
||||
if source == "keyless" && server != "keyless" {
|
||||
want = old
|
||||
}
|
||||
if part == "library" && source == "clear" {
|
||||
// an empty secret is not a clear: it is mostly a
|
||||
// redaction the uploader downloaded and never held
|
||||
want = old
|
||||
}
|
||||
if part == "providers" {
|
||||
p := merged.Providers[0]
|
||||
if p.Key != want || p.BalanceToken != want || (*merged.Searches)[0].Key != want || merged.Library != to.Library {
|
||||
t.Error("provider/search credentials were lost, an explicit clear was ignored, or the library changed")
|
||||
}
|
||||
} else if merged.Library.MCP[0].Env["GITHUB_TOKEN"] != want || merged.Library.MCP[0].Headers["Authorization"] != want || !reflect.DeepEqual(merged.Providers, to.Providers) {
|
||||
t.Error("library credentials were lost, an explicit clear was ignored, or providers changed")
|
||||
}
|
||||
plain, _ := json.Marshal(merged)
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(plain, &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if (merged.Keys || string(fields[part+"Keys"]) == "true") != (server != "keyless" || source != "keyless") {
|
||||
t.Error("the selected part did not retain its own credential scope")
|
||||
}
|
||||
afterTo, _ := json.Marshal(to)
|
||||
afterFrom, _ := json.Marshal(from)
|
||||
if !slices.Equal(beforeTo, afterTo) || !slices.Equal(beforeFrom, afterFrom) {
|
||||
t.Error("taking a part mutated an input bundle")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user