Skip to content

Commit d7262c2

Browse files
committed
fix: allow empty policies when editing access keys
Let admin, LDAP and OpenID access-key edits send explicit empty session policy documents to reset inline policies. Omitting --policy still leaves the existing policy unchanged. Validate a single JSON object without the Policy custom unmarshaler before strict policy parsing. Reject null, trailing input and unknown fields so malformed documents cannot accidentally request a policy reset. Keep named-policy emptiness and Version checks. Cover all three edit commands and named-policy writes with 67 CLI subprocess scenarios, including decrypted request payloads and rejection before network requests. Validation: focused access-key, named-policy and policy-parser tests pass; gofmt and git diff --check pass. Signed-off-by: Feng Ruohang <rh@vonng.com>
1 parent ce94c3b commit d7262c2

4 files changed

Lines changed: 216 additions & 7 deletions

File tree

‎cmd/accesskey-edit_test.go‎

Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
// Copyright (c) 2026 PGSTY
2+
//
3+
// This file is part of the Silo object storage client.
4+
//
5+
// This program is free software: you can redistribute it and/or modify
6+
// it under the terms of the GNU Affero General Public License as published by
7+
// the Free Software Foundation, either version 3 of the License, or
8+
// (at your option) any later version.
9+
//
10+
// This program is distributed in the hope that it will be useful,
11+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
12+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13+
// GNU Affero General Public License for more details.
14+
//
15+
// You should have received a copy of the GNU Affero General Public License
16+
// along with this program. If not, see <http://www.gnu.org/licenses/>.
17+
18+
package cmd
19+
20+
import (
21+
"encoding/json"
22+
"io"
23+
"net/http"
24+
"net/http/httptest"
25+
"os"
26+
"path/filepath"
27+
"strings"
28+
"sync/atomic"
29+
"testing"
30+
31+
"github.com/minio/madmin-go/v3"
32+
)
33+
34+
func TestAccesskeyEditPolicyCLI(t *testing.T) {
35+
commands := []struct {
36+
name string
37+
args []string
38+
}{
39+
{"admin", []string{"admin", "accesskey", "edit"}},
40+
{"ldap", []string{"idp", "ldap", "accesskey", "edit"}},
41+
{"openid", []string{"idp", "openid", "accesskey", "edit"}},
42+
}
43+
cases := []struct {
44+
name, document, wantError string
45+
omitPolicy, missingFile bool
46+
}{
47+
{name: "omitted policy", omitPolicy: true},
48+
{name: "empty object", document: `{}`},
49+
{name: "empty statements", document: `{"Statement":[]}`},
50+
{name: "versioned empty statements", document: `{"Version":"2012-10-17","Statement":[]}`},
51+
{name: "inline policy", document: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::bucket/*"]}]}`},
52+
{name: "inline policy without version", document: `{"Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::bucket/*"]}]}`},
53+
{name: "missing file", missingFile: true, wantError: "unable to read the policy document"},
54+
{name: "empty file", wantError: "unable to parse the policy document"},
55+
{name: "whitespace", document: " \n\t", wantError: "unable to parse the policy document"},
56+
{name: "malformed JSON", document: `{"Statement":`, wantError: "unable to parse the policy document"},
57+
{name: "null", document: `null`, wantError: "unable to parse the policy document"},
58+
{name: "array", document: `[]`, wantError: "unable to parse the policy document"},
59+
{name: "unknown field", document: `{"Statment":[]}`, wantError: "unable to parse the policy document"},
60+
{name: "trailing document", document: `{} {}`, wantError: "unable to parse the policy document"},
61+
{name: "trailing garbage", document: `{} invalid`, wantError: "unable to parse the policy document"},
62+
{name: "invalid version", document: `{"Version":"invalid","Statement":[]}`, wantError: "unable to parse the policy document"},
63+
{name: "invalid statement type", document: `{"Statement":1}`, wantError: "unable to parse the policy document"},
64+
{name: "invalid statement", document: `{"Statement":[{}]}`, wantError: "unable to parse the policy document"},
65+
{name: "bare ARN", document: `{"Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::"]}]}`, wantError: "unable to parse the policy document"},
66+
{name: "conflicting resources", document: `{"Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::bucket/*"],"NotResource":["arn:aws:s3:::other/*"]}]}`, wantError: "unable to parse the policy document"},
67+
}
68+
for _, command := range commands {
69+
for _, tc := range cases {
70+
t.Run(command.name+"/"+tc.name, func(t *testing.T) {
71+
var requests atomic.Int32
72+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
73+
requests.Add(1)
74+
if tc.wantError != "" {
75+
t.Error("invalid policy reached the server")
76+
w.WriteHeader(http.StatusBadRequest)
77+
return
78+
}
79+
if r.Method != http.MethodPost || r.URL.Path != "/minio/admin/v3/update-service-account" || r.URL.Query().Get("accessKey") != "test-access-key" {
80+
t.Errorf("unexpected edit request: %s %s", r.Method, r.URL)
81+
}
82+
if r.Header.Get("Authorization") == "" {
83+
t.Error("unsigned edit request")
84+
}
85+
body, err := madmin.DecryptData("secret", r.Body)
86+
if err != nil {
87+
t.Errorf("decrypt edit request: %v", err)
88+
w.WriteHeader(http.StatusBadRequest)
89+
return
90+
}
91+
var request map[string]json.RawMessage
92+
if err := json.Unmarshal(body, &request); err != nil {
93+
t.Errorf("decode edit request: %v", err)
94+
w.WriteHeader(http.StatusBadRequest)
95+
return
96+
}
97+
if tc.omitPolicy {
98+
if _, ok := request["newPolicy"]; ok {
99+
t.Errorf("omitted --policy must not change the policy: %s", body)
100+
}
101+
if string(request["newName"]) != `"renamed"` {
102+
t.Errorf("name edit lost: %s", body)
103+
}
104+
} else if string(request["newPolicy"]) != tc.document {
105+
t.Errorf("policy changed: got %s, want %s", request["newPolicy"], tc.document)
106+
}
107+
w.WriteHeader(http.StatusNoContent)
108+
}))
109+
defer server.Close()
110+
111+
args := append([]string{}, command.args...)
112+
if tc.omitPolicy {
113+
args = append(args, "--name", "renamed")
114+
} else {
115+
filename := filepath.Join(t.TempDir(), "policy.json")
116+
if !tc.missingFile {
117+
if err := os.WriteFile(filename, []byte(tc.document), 0o600); err != nil {
118+
t.Fatal(err)
119+
}
120+
}
121+
args = append(args, "--policy", filename)
122+
}
123+
args = append(args, "b4", "test-access-key")
124+
result := runChecksumVerifyCLI(t, server.URL, nil, args...)
125+
if tc.wantError != "" {
126+
output := string(result.stdout) + string(result.stderr)
127+
if result.exitCode != 1 || requests.Load() != 0 || !strings.Contains(output, tc.wantError) {
128+
t.Fatalf("exit=%d requests=%d, want local rejection containing %q; output=%s", result.exitCode, requests.Load(), tc.wantError, output)
129+
}
130+
} else if result.exitCode != 0 || requests.Load() != 1 {
131+
t.Fatalf("exit=%d requests=%d, want success with one edit request; stdout=%s stderr=%s", result.exitCode, requests.Load(), result.stdout, result.stderr)
132+
}
133+
})
134+
}
135+
}
136+
}
137+
138+
func TestNamedPolicyWriteCLI(t *testing.T) {
139+
cases := []struct {
140+
name, document, wantError string
141+
}{
142+
{name: "valid policy", document: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::bucket/*"]}]}`},
143+
{name: "empty object", document: `{}`, wantError: "empty policies are not allowed"},
144+
{name: "empty statements", document: `{"Statement":[]}`, wantError: "empty policies are not allowed"},
145+
{name: "versioned empty statements", document: `{"Version":"2012-10-17","Statement":[]}`, wantError: "empty policies are not allowed"},
146+
{name: "missing version", document: `{"Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::bucket/*"]}]}`, wantError: "policy version cannot be empty"},
147+
{name: "malformed JSON", document: `{"Statement":`, wantError: "Unable to parse policy"},
148+
{name: "unknown field", document: `{"Statment":[]}`, wantError: "unknown field"},
149+
}
150+
for _, tc := range cases {
151+
t.Run(tc.name, func(t *testing.T) {
152+
var requests atomic.Int32
153+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
154+
requests.Add(1)
155+
if tc.wantError != "" {
156+
t.Error("invalid named policy reached the server")
157+
w.WriteHeader(http.StatusBadRequest)
158+
return
159+
}
160+
if r.Method != http.MethodPut || r.URL.Path != "/minio/admin/v3/add-canned-policy" || r.URL.Query().Get("name") != "test-policy" {
161+
t.Errorf("unexpected policy request: %s %s", r.Method, r.URL)
162+
}
163+
body, err := io.ReadAll(r.Body)
164+
if err != nil || string(body) != tc.document {
165+
t.Errorf("policy changed: got %s, want %s; error=%v", body, tc.document, err)
166+
}
167+
w.WriteHeader(http.StatusOK)
168+
}))
169+
defer server.Close()
170+
171+
filename := filepath.Join(t.TempDir(), "policy.json")
172+
if err := os.WriteFile(filename, []byte(tc.document), 0o600); err != nil {
173+
t.Fatal(err)
174+
}
175+
result := runChecksumVerifyCLI(t, server.URL, nil, "admin", "policy", "create", "b4", "test-policy", filename)
176+
if tc.wantError != "" {
177+
output := string(result.stdout) + string(result.stderr)
178+
if result.exitCode != 1 || requests.Load() != 0 || !strings.Contains(output, tc.wantError) {
179+
t.Fatalf("exit=%d requests=%d, want local rejection containing %q; output=%s", result.exitCode, requests.Load(), tc.wantError, output)
180+
}
181+
} else if result.exitCode != 0 || requests.Load() != 1 {
182+
t.Fatalf("exit=%d requests=%d, want success with one policy request; stdout=%s stderr=%s", result.exitCode, requests.Load(), result.stdout, result.stderr)
183+
}
184+
})
185+
}
186+
}

‎cmd/idp-ldap-accesskey-edit.go‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -133,17 +133,14 @@ func accessKeyEditOpts(ctx *cli.Context) madmin.UpdateServiceAccountReq {
133133
}
134134

135135
if policyPath != "" {
136-
// Validate the policy document and ensure it has at least one statement
136+
// An empty policy clears the inline policy and returns the account to its
137+
// inherited policy. Keep validating the document shape strictly.
137138
policyBytes, e := os.ReadFile(policyPath)
138139
fatalIf(probe.NewError(e), "unable to read the policy document")
139140

140-
p, e := parsePolicyForWrite(policyBytes)
141+
_, e = parsePolicyForWrite(policyBytes)
141142
fatalIf(probe.NewError(e), "unable to parse the policy document")
142143

143-
if p.IsEmpty() {
144-
fatalIf(errInvalidArgument(), "empty policies are not allowed")
145-
}
146-
147144
opts.NewPolicy = policyBytes
148145
}
149146

‎cmd/policy-validation.go‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package cmd
1919

2020
import (
2121
"bytes"
22+
"encoding/json"
2223
"errors"
2324

2425
"github.com/pgsty/silo-pkg/v3/policy"
@@ -33,9 +34,24 @@ var _ func(policy.Resource) bool = policy.Resource.IsBareARN
3334
// parsePolicyForWrite applies the strict validation required for new and
3435
// updated policy documents while read paths remain backward-compatible.
3536
func parsePolicyForWrite(policyBytes []byte) (*policy.Policy, error) {
36-
if len(bytes.TrimSpace(policyBytes)) == 0 {
37+
policyBytes = bytes.TrimSpace(policyBytes)
38+
if len(policyBytes) == 0 {
3739
return nil, errors.New("policy input cannot be empty")
3840
}
41+
if policyBytes[0] != '{' || !json.Valid(policyBytes) {
42+
return nil, errors.New("policy input must be a JSON object")
43+
}
44+
45+
// Bypass Policy.UnmarshalJSON so unknown fields cannot turn a misspelled
46+
// document into an empty policy reset.
47+
type policyDocument policy.Policy
48+
var document policyDocument
49+
decoder := json.NewDecoder(bytes.NewReader(policyBytes))
50+
decoder.DisallowUnknownFields()
51+
if err := decoder.Decode(&document); err != nil {
52+
return nil, err
53+
}
54+
3955
return policy.ParseConfigStrict(bytes.NewReader(policyBytes))
4056
}
4157

‎cmd/policy-validation_test.go‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,16 @@ func TestParseNamedPolicyForWriteAppliesNamedPolicyInvariants(t *testing.T) {
6363
name: "valid named policy",
6464
document: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::bucket/*"]}]}`,
6565
},
66+
{
67+
name: "empty object",
68+
document: `{}`,
69+
wantErr: true,
70+
},
71+
{
72+
name: "empty statements without version",
73+
document: `{"Statement":[]}`,
74+
wantErr: true,
75+
},
6676
{
6777
name: "empty policy",
6878
document: `{"Version":"2012-10-17","Statement":[]}`,

0 commit comments

Comments
 (0)