Files
seaweedfs/weed/shell/command_s3_serviceaccount_create.go
Chris Lu 10e7f0f2bc fix(shell): s3.user.provision handles existing users by attaching policy (#9040)
* fix(shell): s3.user.provision handles existing users by attaching policy

Instead of erroring when the user already exists, the command now
creates the policy and attaches it to the existing user via UpdateUser.
Credentials are only generated and displayed for newly created users.

* fix(shell): skip duplicate policy attachment in s3.user.provision

Check if the policy is already attached before appending and calling
UpdateUser, making repeated runs idempotent.

* fix(shell): generate service account ID in s3.serviceaccount.create

The command built a ServiceAccount proto without setting Id, which was
rejected by credential.ValidateServiceAccountId on any real store. Now
generates sa:<parent>:<uuid> matching the format used by the admin UI.

* test(s3): integration tests for s3.* shell commands

Adds TestShell* integration tests covering ~40 previously untested
shell commands: user, accesskey, group, serviceaccount, anonymous,
bucket, policy.attach/detach, config.show, and iam.export/import.

Switches the test cluster's credential store from memory to filer_etc
because the memory store silently drops groups and service accounts
in LoadConfiguration/SaveConfiguration.

* fix(shell): rollback policy on key generation failure in s3.user.provision

If iam.GenerateRandomString or iam.GenerateSecretAccessKey fails after
the policy was persisted, the policy would be left orphaned. Extracts
the rollback logic into a local closure and invokes it on all failure
paths after policy creation for consistency.

* address PR review feedback for s3 shell tests and serviceaccount

- s3.serviceaccount.create: use 16 bytes of randomness (hex-encoded) for
  the service account UUID instead of 4 bytes to eliminate collision risk
- s3.serviceaccount.create: print the actual ID and drop the outdated
  "server-assigned" note (the ID is now client-generated)
- tests: guard createdAK in accesskey rotate/delete subtests so sibling
  failures don't run invalid CLI calls
- tests: requireContains/requireNotContains use t.Fatalf to fail fast
- tests: Provision subtest asserts the "Attached policy" message on the
  second provision call for an existing user
- tests: update extractServiceAccountID comment example to match the
  sa:<parent>:<uuid> format
- tests: drop redundant saID empty-check (extractServiceAccountID fatals)

* test(s3): use t.Fatalf for precondition check in serviceaccount test
2026-04-11 22:30:51 -07:00

145 lines
4.1 KiB
Go

package shell
import (
"context"
"crypto/rand"
"encoding/hex"
"flag"
"fmt"
"io"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/iam"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
"google.golang.org/grpc"
)
func init() {
Commands = append(Commands, &commandS3ServiceAccountCreate{})
}
type commandS3ServiceAccountCreate struct {
}
func (c *commandS3ServiceAccountCreate) Name() string {
return "s3.serviceaccount.create"
}
func (c *commandS3ServiceAccountCreate) Help() string {
return `create a service account for an S3 IAM user
s3.serviceaccount.create -user <parent_user> -description "my app"
s3.serviceaccount.create -user <parent_user> -actions Read,List -expiry 24h
Service accounts are linked to a parent user and can have restricted
permissions (a subset of the parent's actions).
`
}
func (c *commandS3ServiceAccountCreate) HasTag(CommandTag) bool {
return false
}
func (c *commandS3ServiceAccountCreate) Do(args []string, commandEnv *CommandEnv, writer io.Writer) error {
f := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
user := f.String("user", "", "parent user name")
description := f.String("description", "", "optional description")
actions := f.String("actions", "", "comma-separated actions (subset of parent)")
expiry := f.Duration("expiry", 0, "expiration duration (e.g. 24h, 0 = no expiration)")
if err := f.Parse(args); err != nil {
return err
}
if *user == "" {
return fmt.Errorf("-user is required")
}
ak, err := iam.GenerateRandomString(iam.AccessKeyIdLength, iam.CharsetUpper)
if err != nil {
return fmt.Errorf("generate access key: %v", err)
}
sk, err := iam.GenerateSecretAccessKey()
if err != nil {
return fmt.Errorf("generate secret key: %v", err)
}
// Generate a unique service account ID matching the format
// required by credential.ValidateServiceAccountId: sa:<parent>:<uuid>.
// 16 bytes (128 bits) of randomness makes collisions negligible.
var idBytes [16]byte
if _, err := rand.Read(idBytes[:]); err != nil {
return fmt.Errorf("generate service account id: %v", err)
}
saId := fmt.Sprintf("sa:%s:%s", *user, hex.EncodeToString(idBytes[:]))
sa := &iam_pb.ServiceAccount{
Id: saId,
ParentUser: *user,
Description: *description,
Credential: &iam_pb.Credential{
AccessKey: ak,
SecretKey: sk,
Status: iam.AccessKeyStatusActive,
},
CreatedAt: time.Now().Unix(),
}
validActions := map[string]string{
"read": "Read", "write": "Write", "list": "List",
"tagging": "Tagging", "admin": "Admin",
}
if *actions != "" {
seen := make(map[string]struct{})
for _, a := range strings.Split(*actions, ",") {
a = strings.TrimSpace(a)
if a != "" {
canonical, ok := validActions[strings.ToLower(a)]
if !ok {
return fmt.Errorf("invalid action %q: supported actions are Read, Write, List, Tagging, Admin", a)
}
if _, dup := seen[canonical]; dup {
continue
}
seen[canonical] = struct{}{}
sa.Actions = append(sa.Actions, canonical)
}
}
}
if *expiry < 0 {
return fmt.Errorf("-expiry must be >= 0")
}
if *expiry > 0 {
sa.Expiration = time.Now().Add(*expiry).Unix()
}
err = pb.WithGrpcClient(false, 0, func(conn *grpc.ClientConn) error {
client := iam_pb.NewSeaweedIdentityAccessManagementClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err := client.CreateServiceAccount(ctx, &iam_pb.CreateServiceAccountRequest{
ServiceAccount: sa,
})
return err
}, commandEnv.option.FilerAddress.ToGrpcAddress(), false, commandEnv.option.GrpcDialOption)
if err != nil {
return err
}
fmt.Fprintf(writer, "Created service account for user %q\n", *user)
fmt.Fprintf(writer, "ID: %s\n", saId)
fmt.Fprintf(writer, "Access Key: %s\n", ak)
fmt.Fprintf(writer, "Secret Key: %s\n", sk)
if *description != "" {
fmt.Fprintf(writer, "Desc: %s\n", *description)
}
if *expiry > 0 {
fmt.Fprintf(writer, "Expires: %s\n", time.Unix(sa.Expiration, 0).Format(time.RFC3339))
}
fmt.Fprintln(writer)
fmt.Fprintln(writer, "Save these credentials - the secret key cannot be retrieved later.")
return nil
}