build / build (push) Successful in 8m41s
0004-vault-atomic-update-user.patch makes the Vault IAM backend's UpdateUserAccount -- what admin update-user, and so every key rotation, runs -- one KV v2 write with cas set to the version it read, retried from a fresh read on a check-and-set conflict (up to 5 attempts). Upstream deleted the entry and created it again: in between, another instance on the same KV path whose IAM cache missed answered InvalidAccessKeyId, a failure between the two calls lost the account, and two updates at once lost one of them. Touches only auth/iam_vault.go and a new auth/iam_vault_update_test.go. tests/vault-update/proof.sh proves it on leil-rig against an OpenBao dev server, with two gateways on one KV path and gateway A's OpenBao calls held 3 s by a proxy so upstream's gap can be observed. On leil-test-1: patched 20 passed, 0 failed; 0001-0003 control 13 passed, 7 failed (entry missing 3.00 s, 28 InvalidAccessKeyId on the second gateway, concurrent rotation lost, account gone after a refused write). go test on the node: 35 of 35 packages ok. docs/vault-atomic-update.md has the problem, the change, the proof and its result; README and the multi-version pipeline doc point at it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
489 lines
16 KiB
Diff
489 lines
16 KiB
Diff
From 285a0f55757c668982cc5a3c3bf5e27b803fcc18 Mon Sep 17 00:00:00 2001
|
|
From: s3-gateway CI <ci@s3-gateway.local>
|
|
Date: Wed, 11 Nov 2026 01:30:01 -0600
|
|
Subject: [PATCH 4/4] auth: update a Vault IAM account with one check-and-set
|
|
write
|
|
|
|
UpdateUserAccount on the Vault backend read the account, deleted its
|
|
KV entry (metadata and every version) and created it again with cas=0.
|
|
Two things followed:
|
|
|
|
- While a rotation ran the account did not exist. Another gateway
|
|
instance on the same KV path whose IAM cache missed in that gap -- an
|
|
expired entry, or a key it had not cached yet -- found no entry,
|
|
never caches a miss, and answered InvalidAccessKeyId.
|
|
- A failure between the delete and the create (OpenBao unreachable, a
|
|
token that could no longer write, the process stopping) lost the
|
|
account for good.
|
|
|
|
The update is now one KV v2 write. The entry is read together with its
|
|
version, the change applied, and the result written back with cas set
|
|
to that version. The account exists throughout, and a write that fails
|
|
leaves it as it was. If another writer changed the entry in between,
|
|
OpenBao refuses the write with a check-and-set error and the update
|
|
starts again from a fresh read, up to five times; after that it fails
|
|
with the last conflict. An account deleted in between stays deleted:
|
|
the retry's read answers ErrNoSuchUser, as does an update of an account
|
|
that never existed.
|
|
|
|
A 403 on the read or the write logs in again and retries once, as the
|
|
backend's other calls do. The read is shared with GetUserAccount
|
|
(readAccountEntry), whose behaviour is unchanged; CreateAccount,
|
|
DeleteUserAccount and ListUserAccounts are untouched.
|
|
|
|
KV v2 now keeps an account's previous versions, earlier secrets
|
|
included, up to the mount's max_versions; the delete used to wipe them.
|
|
---
|
|
auth/iam_vault.go | 103 ++++++++++--
|
|
auth/iam_vault_update_test.go | 284 ++++++++++++++++++++++++++++++++++
|
|
2 files changed, 373 insertions(+), 14 deletions(-)
|
|
create mode 100644 auth/iam_vault_update_test.go
|
|
|
|
diff --git a/auth/iam_vault.go b/auth/iam_vault.go
|
|
index c41747f..0b638c4 100644
|
|
--- a/auth/iam_vault.go
|
|
+++ b/auth/iam_vault.go
|
|
@@ -240,31 +240,41 @@ func (vt *VaultIAMService) GetUserAccount(access string) (Account, error) {
|
|
if vt.rootAcc.Access == access {
|
|
return vt.rootAcc, nil
|
|
}
|
|
+ resp, err := vt.readAccountEntry(access)
|
|
+ if err != nil {
|
|
+ return Account{}, err
|
|
+ }
|
|
+ acc, err := parseVaultUserAccount(resp.Data.Data, access)
|
|
+ if err != nil {
|
|
+ return Account{}, err
|
|
+ }
|
|
+ return acc, nil
|
|
+}
|
|
+
|
|
+// readAccountEntry reads the KV entry of access, data and metadata, logging
|
|
+// in again and retrying once on a 403. A missing entry is ErrNoSuchUser.
|
|
+func (vt *VaultIAMService) readAccountEntry(access string) (*vault.Response[schema.KvV2ReadResponse], error) {
|
|
resp, err := vt.client.Secrets.KvV2Read(context.Background(),
|
|
vt.secretStoragePath+"/"+access, vt.kvReqOpts...)
|
|
if err != nil {
|
|
reauthErr := vt.reAuthIfNeeded(err)
|
|
if reauthErr != nil {
|
|
if vault.IsErrorStatus(err, http.StatusNotFound) {
|
|
- return Account{}, ErrNoSuchUser
|
|
+ return nil, ErrNoSuchUser
|
|
}
|
|
- return Account{}, reauthErr
|
|
+ return nil, reauthErr
|
|
}
|
|
// retry once after re-auth
|
|
resp, err = vt.client.Secrets.KvV2Read(context.Background(),
|
|
vt.secretStoragePath+"/"+access, vt.kvReqOpts...)
|
|
if err != nil {
|
|
if vault.IsErrorStatus(err, http.StatusNotFound) {
|
|
- return Account{}, ErrNoSuchUser
|
|
+ return nil, ErrNoSuchUser
|
|
}
|
|
- return Account{}, err
|
|
+ return nil, err
|
|
}
|
|
}
|
|
- acc, err := parseVaultUserAccount(resp.Data.Data, access)
|
|
- if err != nil {
|
|
- return Account{}, err
|
|
- }
|
|
- return acc, nil
|
|
+ return resp, nil
|
|
}
|
|
|
|
// ResolveAccounts returns the subset of accessKeyIDs that do not exist.
|
|
@@ -272,21 +282,71 @@ func (vt *VaultIAMService) ResolveAccounts(accessKeyIDs []string) ([]string, err
|
|
return resolveAccountsByLookup(accessKeyIDs, vt.GetUserAccount)
|
|
}
|
|
|
|
+// vaultUpdateAttempts bounds how often UpdateUserAccount reads an account and
|
|
+// writes it back when another writer changes the entry in between.
|
|
+const vaultUpdateAttempts = 5
|
|
+
|
|
+// UpdateUserAccount changes an account with one check-and-set write of its KV
|
|
+// entry, at the version it was read at: the account exists throughout, and a
|
|
+// write that fails leaves it as it was. If another writer changed the entry
|
|
+// in between, the write is refused and the update starts again from a fresh
|
|
+// read, up to vaultUpdateAttempts times.
|
|
func (vt *VaultIAMService) UpdateUserAccount(access string, props MutableProps) error {
|
|
- acc, err := vt.GetUserAccount(access)
|
|
+ var err error
|
|
+ for range vaultUpdateAttempts {
|
|
+ err = vt.updateAccountEntry(access, props)
|
|
+ if !isVaultCASConflict(err) {
|
|
+ return err
|
|
+ }
|
|
+ }
|
|
+ return fmt.Errorf("update user %q: its entry changed during each of %d attempts: %w",
|
|
+ access, vaultUpdateAttempts, err)
|
|
+}
|
|
+
|
|
+// updateAccountEntry reads the entry of access, applies props, and writes it
|
|
+// back with cas set to the version it read.
|
|
+func (vt *VaultIAMService) updateAccountEntry(access string, props MutableProps) error {
|
|
+ resp, err := vt.readAccountEntry(access)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
- updateAcc(&acc, props)
|
|
- err = vt.DeleteUserAccount(access)
|
|
+ acc, err := parseVaultUserAccount(resp.Data.Data, access)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
- err = vt.CreateAccount(acc)
|
|
+ version, err := parseVaultEntryVersion(resp.Data.Metadata)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
- return nil
|
|
+ updateAcc(&acc, props)
|
|
+
|
|
+ req := schema.KvV2WriteRequest{
|
|
+ Data: map[string]any{
|
|
+ access: acc,
|
|
+ },
|
|
+ Options: map[string]any{
|
|
+ "cas": version,
|
|
+ },
|
|
+ }
|
|
+ _, err = vt.client.Secrets.KvV2Write(context.Background(),
|
|
+ vt.secretStoragePath+"/"+access, req, vt.kvReqOpts...)
|
|
+ if err == nil || isVaultCASConflict(err) {
|
|
+ return err
|
|
+ }
|
|
+ reauthErr := vt.reAuthIfNeeded(err)
|
|
+ if reauthErr != nil {
|
|
+ return reauthErr
|
|
+ }
|
|
+ // retry once after re-auth
|
|
+ _, err = vt.client.Secrets.KvV2Write(context.Background(),
|
|
+ vt.secretStoragePath+"/"+access, req, vt.kvReqOpts...)
|
|
+ return err
|
|
+}
|
|
+
|
|
+// isVaultCASConflict reports a KV write refused because its cas option no
|
|
+// longer matched the entry's current version.
|
|
+func isVaultCASConflict(err error) bool {
|
|
+ return err != nil && strings.Contains(err.Error(), "check-and-set")
|
|
}
|
|
|
|
func (vt *VaultIAMService) DeleteUserAccount(access string) error {
|
|
@@ -346,6 +406,21 @@ func (vt *VaultIAMService) Shutdown() error {
|
|
|
|
var errInvalidUser error = errors.New("invalid user account entry in secrets engine")
|
|
|
|
+var errInvalidVersion error = errors.New("invalid version of user account entry in secrets engine")
|
|
+
|
|
+// parseVaultEntryVersion returns the KV v2 version a read found the entry at.
|
|
+func parseVaultEntryVersion(metadata map[string]any) (int64, error) {
|
|
+ versionJson, ok := metadata["version"].(json.Number)
|
|
+ if !ok {
|
|
+ return 0, errInvalidVersion
|
|
+ }
|
|
+ version, err := versionJson.Int64()
|
|
+ if err != nil || version < 1 {
|
|
+ return 0, errInvalidVersion
|
|
+ }
|
|
+ return version, nil
|
|
+}
|
|
+
|
|
func parseVaultUserAccount(data map[string]any, access string) (acc Account, err error) {
|
|
usrAcc, ok := data[access].(map[string]any)
|
|
if !ok {
|
|
diff --git a/auth/iam_vault_update_test.go b/auth/iam_vault_update_test.go
|
|
new file mode 100644
|
|
index 0000000..29e68b1
|
|
--- /dev/null
|
|
+++ b/auth/iam_vault_update_test.go
|
|
@@ -0,0 +1,284 @@
|
|
+// Copyright 2026 Versity Software
|
|
+// This file is licensed under the Apache License, Version 2.0
|
|
+// (the "License"); you may not use this file except in compliance
|
|
+// with the License. You may obtain a copy of the License at
|
|
+//
|
|
+// http://www.apache.org/licenses/LICENSE-2.0
|
|
+//
|
|
+// Unless required by applicable law or agreed to in writing,
|
|
+// software distributed under the License is distributed on an
|
|
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
+// KIND, either express or implied. See the License for the
|
|
+// specific language governing permissions and limitations
|
|
+// under the License.
|
|
+
|
|
+package auth
|
|
+
|
|
+import (
|
|
+ "encoding/json"
|
|
+ "fmt"
|
|
+ "net/http"
|
|
+ "net/http/httptest"
|
|
+ "strings"
|
|
+ "sync"
|
|
+ "testing"
|
|
+
|
|
+ "github.com/stretchr/testify/assert"
|
|
+)
|
|
+
|
|
+// fakeVaultKV is as much of Vault as VaultIAMService uses: AppRole login and
|
|
+// a KV v2 mount at kv-v2/ with versioned entries under users/, check-and-set
|
|
+// included. Requests carrying anything but the last login's token get 403.
|
|
+type fakeVaultKV struct {
|
|
+ mu sync.Mutex
|
|
+ entries map[string]fakeVaultEntry
|
|
+ token string
|
|
+ logins int
|
|
+ reads int
|
|
+ writes int
|
|
+ cas []int64 // the cas option of every data write that reached the check
|
|
+ deletes int
|
|
+
|
|
+ // before, if set, runs at the start of every KV request, with the
|
|
+ // request's operation ("read", "write" or "delete") and its count so far.
|
|
+ before func(f *fakeVaultKV, op string, n int)
|
|
+}
|
|
+
|
|
+type fakeVaultEntry struct {
|
|
+ acc Account
|
|
+ version int64
|
|
+}
|
|
+
|
|
+func (f *fakeVaultKV) put(acc Account) {
|
|
+ e := f.entries[acc.Access]
|
|
+ f.entries[acc.Access] = fakeVaultEntry{acc: acc, version: e.version + 1}
|
|
+}
|
|
+
|
|
+func (f *fakeVaultKV) revoke() { f.token = "revoked" }
|
|
+
|
|
+func (f *fakeVaultKV) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
+ f.mu.Lock()
|
|
+ defer f.mu.Unlock()
|
|
+
|
|
+ reply := func(status int, body any) {
|
|
+ w.Header().Set("Content-Type", "application/json")
|
|
+ w.WriteHeader(status)
|
|
+ json.NewEncoder(w).Encode(body)
|
|
+ }
|
|
+ vaultErr := func(status int, msg ...string) {
|
|
+ reply(status, map[string]any{"errors": append([]string{}, msg...)})
|
|
+ }
|
|
+
|
|
+ if r.Method == http.MethodPost && r.URL.Path == "/v1/auth/approle/login" {
|
|
+ f.logins++
|
|
+ f.token = fmt.Sprintf("token-%d", f.logins)
|
|
+ reply(http.StatusOK, map[string]any{"data": nil, "auth": map[string]any{"client_token": f.token}})
|
|
+ return
|
|
+ }
|
|
+
|
|
+ var op, access string
|
|
+ switch {
|
|
+ case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/v1/kv-v2/data/users/"):
|
|
+ op, access = "read", strings.TrimPrefix(r.URL.Path, "/v1/kv-v2/data/users/")
|
|
+ f.reads++
|
|
+ case r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/v1/kv-v2/data/users/"):
|
|
+ op, access = "write", strings.TrimPrefix(r.URL.Path, "/v1/kv-v2/data/users/")
|
|
+ f.writes++
|
|
+ case r.Method == http.MethodDelete && strings.HasPrefix(r.URL.Path, "/v1/kv-v2/metadata/users/"):
|
|
+ op, access = "delete", strings.TrimPrefix(r.URL.Path, "/v1/kv-v2/metadata/users/")
|
|
+ f.deletes++
|
|
+ default:
|
|
+ vaultErr(http.StatusNotFound)
|
|
+ return
|
|
+ }
|
|
+ if f.before != nil {
|
|
+ n := map[string]int{"read": f.reads, "write": f.writes, "delete": f.deletes}[op]
|
|
+ f.before(f, op, n)
|
|
+ }
|
|
+ if r.Header.Get("X-Vault-Token") != f.token {
|
|
+ vaultErr(http.StatusForbidden, "permission denied")
|
|
+ return
|
|
+ }
|
|
+
|
|
+ e, found := f.entries[access]
|
|
+ switch op {
|
|
+ case "read":
|
|
+ if !found {
|
|
+ vaultErr(http.StatusNotFound)
|
|
+ return
|
|
+ }
|
|
+ reply(http.StatusOK, map[string]any{"data": map[string]any{
|
|
+ "data": map[string]any{access: e.acc},
|
|
+ "metadata": map[string]any{"version": e.version},
|
|
+ }})
|
|
+ case "write":
|
|
+ var req struct {
|
|
+ Data map[string]Account `json:"data"`
|
|
+ Options struct {
|
|
+ CAS *int64 `json:"cas"`
|
|
+ } `json:"options"`
|
|
+ }
|
|
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
+ vaultErr(http.StatusBadRequest, err.Error())
|
|
+ return
|
|
+ }
|
|
+ if req.Options.CAS == nil {
|
|
+ vaultErr(http.StatusBadRequest, "test fake: write without cas")
|
|
+ return
|
|
+ }
|
|
+ f.cas = append(f.cas, *req.Options.CAS)
|
|
+ if *req.Options.CAS != e.version {
|
|
+ vaultErr(http.StatusBadRequest, "check-and-set parameter did not match the current version")
|
|
+ return
|
|
+ }
|
|
+ f.put(req.Data[access])
|
|
+ reply(http.StatusOK, map[string]any{"data": map[string]any{"version": e.version + 1}})
|
|
+ case "delete":
|
|
+ delete(f.entries, access)
|
|
+ w.WriteHeader(http.StatusNoContent)
|
|
+ }
|
|
+}
|
|
+
|
|
+func TestVaultIAMServiceUpdateUserAccount(t *testing.T) {
|
|
+ stored := Account{Access: "user1", Secret: "old-secret", Role: RoleUser, UserID: 74990, GroupID: 74991, ProjectID: 7}
|
|
+ newSecret := "new-secret"
|
|
+ rotated := stored
|
|
+ rotated.Secret = newSecret
|
|
+ otherWriter := func(f *fakeVaultKV) { // another instance changes the account's project
|
|
+ acc := f.entries["user1"].acc
|
|
+ acc.ProjectID++
|
|
+ f.put(acc)
|
|
+ }
|
|
+
|
|
+ tests := []struct {
|
|
+ name string
|
|
+ stored []Account
|
|
+ before func(f *fakeVaultKV, op string, n int)
|
|
+ wantErr error // compared with ==
|
|
+ wantErrText string // or contained in the error
|
|
+ wantAcc *Account
|
|
+ wantVersion int64
|
|
+ wantCAS []int64
|
|
+ wantLogins int
|
|
+ }{
|
|
+ {
|
|
+ name: "one write at the version read",
|
|
+ stored: []Account{stored},
|
|
+ wantAcc: &rotated,
|
|
+ wantVersion: 2,
|
|
+ wantCAS: []int64{1},
|
|
+ wantLogins: 1,
|
|
+ },
|
|
+ {
|
|
+ name: "a conflict, then a retry from a fresh read",
|
|
+ stored: []Account{stored},
|
|
+ before: func(f *fakeVaultKV, op string, n int) {
|
|
+ if op == "write" && n == 1 {
|
|
+ otherWriter(f)
|
|
+ }
|
|
+ },
|
|
+ wantAcc: &Account{Access: "user1", Secret: newSecret, Role: RoleUser, UserID: 74990, GroupID: 74991, ProjectID: 8},
|
|
+ wantVersion: 3,
|
|
+ wantCAS: []int64{1, 2},
|
|
+ wantLogins: 1,
|
|
+ },
|
|
+ {
|
|
+ name: "conflicts until the attempts run out",
|
|
+ stored: []Account{stored},
|
|
+ before: func(f *fakeVaultKV, op string, n int) {
|
|
+ if op == "write" {
|
|
+ otherWriter(f)
|
|
+ }
|
|
+ },
|
|
+ wantErrText: "check-and-set",
|
|
+ wantAcc: &Account{Access: "user1", Secret: "old-secret", Role: RoleUser, UserID: 74990, GroupID: 74991, ProjectID: 12},
|
|
+ wantVersion: 6,
|
|
+ wantCAS: []int64{1, 2, 3, 4, 5}, // vaultUpdateAttempts
|
|
+ wantLogins: 1,
|
|
+ },
|
|
+ {
|
|
+ name: "no such user",
|
|
+ wantErr: ErrNoSuchUser,
|
|
+ wantLogins: 1,
|
|
+ },
|
|
+ {
|
|
+ name: "deleted between the read and the write",
|
|
+ stored: []Account{stored},
|
|
+ before: func(f *fakeVaultKV, op string, n int) {
|
|
+ if op == "write" && n == 1 {
|
|
+ delete(f.entries, "user1")
|
|
+ }
|
|
+ },
|
|
+ wantErr: ErrNoSuchUser,
|
|
+ wantCAS: []int64{1},
|
|
+ wantLogins: 1,
|
|
+ },
|
|
+ {
|
|
+ name: "a re-login after a 403 on the read",
|
|
+ stored: []Account{stored},
|
|
+ before: func(f *fakeVaultKV, op string, n int) {
|
|
+ if op == "read" && n == 1 {
|
|
+ f.revoke()
|
|
+ }
|
|
+ },
|
|
+ wantAcc: &rotated,
|
|
+ wantVersion: 2,
|
|
+ wantCAS: []int64{1},
|
|
+ wantLogins: 2,
|
|
+ },
|
|
+ {
|
|
+ name: "a re-login after a 403 on the write",
|
|
+ stored: []Account{stored},
|
|
+ before: func(f *fakeVaultKV, op string, n int) {
|
|
+ if op == "write" && n == 1 {
|
|
+ f.revoke()
|
|
+ }
|
|
+ },
|
|
+ wantAcc: &rotated,
|
|
+ wantVersion: 2,
|
|
+ wantCAS: []int64{1},
|
|
+ wantLogins: 2,
|
|
+ },
|
|
+ }
|
|
+
|
|
+ for _, tt := range tests {
|
|
+ t.Run(tt.name, func(t *testing.T) {
|
|
+ fake := &fakeVaultKV{entries: map[string]fakeVaultEntry{}}
|
|
+ for _, acc := range tt.stored {
|
|
+ fake.put(acc)
|
|
+ }
|
|
+ srv := httptest.NewServer(fake)
|
|
+ defer srv.Close()
|
|
+
|
|
+ iam, err := NewVaultIAMService(Account{Access: "root"}, srv.URL, "", "users", "", "", "", "", "", "role", "role-secret", "", "", "")
|
|
+ assert.NoError(t, err)
|
|
+
|
|
+ fake.mu.Lock()
|
|
+ fake.before = tt.before
|
|
+ fake.mu.Unlock()
|
|
+
|
|
+ err = iam.UpdateUserAccount("user1", MutableProps{Secret: &newSecret})
|
|
+ switch {
|
|
+ case tt.wantErr != nil:
|
|
+ assert.Equal(t, tt.wantErr, err)
|
|
+ case tt.wantErrText != "":
|
|
+ assert.ErrorContains(t, err, tt.wantErrText)
|
|
+ default:
|
|
+ assert.NoError(t, err)
|
|
+ }
|
|
+
|
|
+ fake.mu.Lock()
|
|
+ defer fake.mu.Unlock()
|
|
+ e, found := fake.entries["user1"]
|
|
+ if tt.wantAcc == nil {
|
|
+ assert.False(t, found, "the update made an account")
|
|
+ } else if assert.True(t, found, "the account is gone") {
|
|
+ assert.Equal(t, *tt.wantAcc, e.acc)
|
|
+ assert.Equal(t, tt.wantVersion, e.version)
|
|
+ }
|
|
+ assert.Equal(t, tt.wantCAS, fake.cas)
|
|
+ assert.Zero(t, fake.deletes, "the update deleted the entry")
|
|
+ assert.Equal(t, tt.wantLogins, fake.logins)
|
|
+ })
|
|
+ }
|
|
+}
|
|
--
|
|
2.49.0.windows.1
|
|
|