migrate IAM policies to multi-file storage (#8114)
* Add IAM gRPC service definition - Add GetConfiguration/PutConfiguration for config management - Add CreateUser/GetUser/UpdateUser/DeleteUser/ListUsers for user management - Add CreateAccessKey/DeleteAccessKey/GetUserByAccessKey for access key management - Methods mirror existing IAM HTTP API functionality * Add IAM gRPC handlers on filer server - Implement IamGrpcServer with CredentialManager integration - Handle configuration get/put operations - Handle user CRUD operations - Handle access key create/delete operations - All methods delegate to CredentialManager for actual storage * Wire IAM gRPC service to filer server - Add CredentialManager field to FilerOption and FilerServer - Import credential store implementations in filer command - Initialize CredentialManager from credential.toml if available - Register IAM gRPC service on filer gRPC server - Enable credential management via gRPC alongside existing filer services * Regenerate IAM protobuf with gRPC service methods * fix: compilation error in DeleteUser * fix: address code review comments for IAM migration * feat: migrate policies to multi-file layout and fix identity duplicated content * refactor: remove configuration.json and migrate Service Accounts to multi-file layout * refactor: standardize Service Accounts as distinct store entities and fix Admin Server persistence * config: set ServiceAccountsDirectory to /etc/iam/service_accounts * Fix Chrome dialog auto-dismiss with Bootstrap modals - Add modal-alerts.js library with Bootstrap modal replacements - Replace all 15 confirm() calls with showConfirm/showDeleteConfirm - Auto-override window.alert() for all alert() calls - Fixes Chrome 132+ aggressively blocking native dialogs * Upgrade Bootstrap from 5.3.2 to 5.3.8 * Fix syntax error in object_store_users.templ - remove duplicate closing braces * create policy * display errors * migrate to multi-file policies * address PR feedback: use showDeleteConfirm and showErrorMessage in policies.templ, refine migration check * Update policies_templ.go * add service account to iam grpc * iam: fix potential path traversal in policy names by validating name pattern * iam: add GetServiceAccountByAccessKey to CredentialStore interface * iam: implement service account support for PostgresStore Includes full CRUD operations and efficient lookup by access key. * iam: implement GetServiceAccountByAccessKey for filer_etc, grpc, and memory stores Provides efficient lookup of service accounts by access key where possible, with linear scan fallbacks for file-based stores. * iam: remove filer_multiple support Deleted its implementation and references in imports, scaffold config, and core interface constants. Redundant with filer_etc. * clear comment * dash: robustify service account construction - Guard against nil sa.Credential when constructing responses - Fix Expiration logic to only set if > 0, avoiding Unix epoch 1970 - Ensure consistency across Get, Create, and Update handlers * credential/filer_etc: improve error propagation in configuration handlers - Return error from loadServiceAccountsFromMultiFile to callers - Ensure listEntries errors in SaveConfiguration (cleanup logic) are propagated unless they are "not found" failures. - Fixes potential silent failures during IAM configuration sync. * credential/filer_etc: add existence check to CreateServiceAccount Ensures consistency with other stores by preventing accidental overwrite of existing service accounts during creation. * credential/memory: improve store robustness and Reset logic - Enforce ID immutability in UpdateServiceAccount to prevent orphans - Update Reset() to also clear the policies map, ensuring full state cleanup for tests. * dash: improve service account robustness and policy docs - Wrap parent user lookup errors to preserve context - Strictly validate Status field in UpdateServiceAccount - Add deprecation comments to legacy policy management methods * credential/filer_etc: protect against path traversal in service accounts Implemented ID validation (alphanumeric, underscores, hyphens) and applied it to Get, Save, and Delete operations to ensure no directory traversal via saId.json filenames. * credential/postgres: improve robustness and cleanup comments - Removed brainstorming comments in GetServiceAccountByAccessKey - Added missing rows.Err() check during iteration - Properly propagate Scan and Unmarshal errors instead of swallowing them * admin: unify UI alerts and confirmations using Bootstrap modals - Updated modal-alerts.js with improved automated alert type detection - Replaced native alert() and confirm() with showAlert(), showConfirm(), and showDeleteConfirm() across various Templ components - Improved UX for delete operations by providing better context and styling - Ensured consistent error reporting across IAM and Maintenance views * admin: additional UI consistency fixes for alerts and confirmations - Replaced native alert() and confirm() with Bootstrap modals in: - EC volumes (repair flow) - Collection details (repair flow) - File browser (properties and delete) - Maintenance config schema (save and reset) - Improved delete confirmation in file browser with item context - Ensured consistent success/error/info styling for all feedbacks * make * iam: add GetServiceAccountByAccessKey RPC and update GetConfiguration * iam: implement GetServiceAccountByAccessKey on server and client * iam: centralize policy and service account validation * iam: optimize MemoryStore service account lookups with indexing * iam: fix postgres service_accounts table and optimize lookups * admin: refactor modal alerts and clean up dashboard logic * admin: fix EC shards table layout mismatch * admin: URL-encode IAM path parameters for safety * admin: implement pauseWorker logic in maintenance view * iam: add rows.Err() check to postgres ListServiceAccounts * iam: standardize ErrServiceAccountNotFound across credential stores * iam: map ErrServiceAccountNotFound to codes.NotFound in DeleteServiceAccount * iam: refine service account store logic, errors and schema * iam: add validation to GetServiceAccountByAccessKey * admin: refine modal titles and ensure URL safety * admin: address bot review comments for alerts and async usage * iam: fix syntax error by restoring missing function declaration * [FilerEtcStore] improve error handling in CreateServiceAccount Refine error handling to provide clearer messages when checking for existing service accounts. * [PostgresStore] add nil guards and validation to service account methods Ensure input parameters are not nil and required IDs are present to prevent runtime panics and ensure data integrity. * [JS] add shared IAM utility script Consolidate common IAM operations like deleteUser and deleteAccessKey into a shared utility script for better maintainability. * [View] include shared IAM utilities in layout Include iam-utils.js in the main layout to make IAM functions available across all administrative pages. * [View] refactor IAM logic and restore async in EC Shards view Remove redundant local IAM functions and ensure that delete confirmation callbacks are properly marked as async. * [View] consolidate IAM logic in Object Store Users view Remove redundant local definitions of deleteUser and deleteAccessKey, relying on the shared utilities instead. * [View] update generated templ files for UI consistency * credential/postgres: remove redundant name column from service_accounts table The id is already used as the unique identifier and was being copied to the name column. This removes the name column from the schema and updates the INSERT/UPDATE queries. * credential/filer_etc: improve logging for policy migration failures Added Errorf log if AtomicRenameEntry fails during migration to ensure visibility of common failure points. * credential: allow uppercase characters in service account ID username Updated ServiceAccountIdPattern to allow [A-Za-z0-9_-]+ for the username component, matching the actual service account creation logic which uses the parent user name directly. * Update object_store_users_templ.go * admin: fix ec_shards pagination to handle numeric page arguments Updated goToPage in cluster_ec_shards.templ to accept either an Event or a numeric page argument. This prevents errors when goToPage(1) is called directly. Corrected both the .templ source and generated Go code. * credential/filer_etc: improve service account storage robustness Added nil guard to saveServiceAccount, updated GetServiceAccount to return ErrServiceAccountNotFound for empty data, and improved deleteServiceAccount to handle response-level Filer errors.
This commit is contained in:
@@ -56,72 +56,33 @@ func NewCredentialStorePolicyManager(credentialManager *credential.CredentialMan
|
||||
}
|
||||
|
||||
// GetPolicies retrieves all IAM policies via credential store
|
||||
// Deprecated: This method delegates to the credential manager and will be moved/removed in a future release.
|
||||
func (cspm *CredentialStorePolicyManager) GetPolicies(ctx context.Context) (map[string]policy_engine.PolicyDocument, error) {
|
||||
// Get policies from credential store
|
||||
// We'll use the credential store to access the filer indirectly
|
||||
// Since policies are stored separately, we need to access the underlying store
|
||||
store := cspm.credentialManager.GetStore()
|
||||
glog.V(1).Infof("Getting policies from credential store: %T", store)
|
||||
|
||||
// Check if the store supports policy management
|
||||
if policyStore, ok := store.(credential.PolicyManager); ok {
|
||||
glog.V(1).Infof("Store supports policy management, calling GetPolicies")
|
||||
policies, err := policyStore.GetPolicies(ctx)
|
||||
if err != nil {
|
||||
glog.Errorf("Error getting policies from store: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
glog.V(1).Infof("Got %d policies from store", len(policies))
|
||||
return policies, nil
|
||||
} else {
|
||||
// Fallback: use empty policies for stores that don't support policies
|
||||
glog.V(1).Infof("Credential store doesn't support policy management, returning empty policies")
|
||||
return make(map[string]policy_engine.PolicyDocument), nil
|
||||
}
|
||||
return cspm.credentialManager.GetPolicies(ctx)
|
||||
}
|
||||
|
||||
// CreatePolicy creates a new IAM policy via credential store
|
||||
// Deprecated: This method delegates to the credential manager and will be moved/removed in a future release.
|
||||
func (cspm *CredentialStorePolicyManager) CreatePolicy(ctx context.Context, name string, document policy_engine.PolicyDocument) error {
|
||||
store := cspm.credentialManager.GetStore()
|
||||
|
||||
if policyStore, ok := store.(credential.PolicyManager); ok {
|
||||
return policyStore.CreatePolicy(ctx, name, document)
|
||||
}
|
||||
|
||||
return fmt.Errorf("credential store doesn't support policy creation")
|
||||
return cspm.credentialManager.CreatePolicy(ctx, name, document)
|
||||
}
|
||||
|
||||
// UpdatePolicy updates an existing IAM policy via credential store
|
||||
// Deprecated: This method delegates to the credential manager and will be moved/removed in a future release.
|
||||
func (cspm *CredentialStorePolicyManager) UpdatePolicy(ctx context.Context, name string, document policy_engine.PolicyDocument) error {
|
||||
store := cspm.credentialManager.GetStore()
|
||||
|
||||
if policyStore, ok := store.(credential.PolicyManager); ok {
|
||||
return policyStore.UpdatePolicy(ctx, name, document)
|
||||
}
|
||||
|
||||
return fmt.Errorf("credential store doesn't support policy updates")
|
||||
return cspm.credentialManager.UpdatePolicy(ctx, name, document)
|
||||
}
|
||||
|
||||
// DeletePolicy deletes an IAM policy via credential store
|
||||
// Deprecated: This method delegates to the credential manager and will be moved/removed in a future release.
|
||||
func (cspm *CredentialStorePolicyManager) DeletePolicy(ctx context.Context, name string) error {
|
||||
store := cspm.credentialManager.GetStore()
|
||||
|
||||
if policyStore, ok := store.(credential.PolicyManager); ok {
|
||||
return policyStore.DeletePolicy(ctx, name)
|
||||
}
|
||||
|
||||
return fmt.Errorf("credential store doesn't support policy deletion")
|
||||
return cspm.credentialManager.DeletePolicy(ctx, name)
|
||||
}
|
||||
|
||||
// GetPolicy retrieves a specific IAM policy via credential store
|
||||
// Deprecated: This method delegates to the credential manager and will be moved/removed in a future release.
|
||||
func (cspm *CredentialStorePolicyManager) GetPolicy(ctx context.Context, name string) (*policy_engine.PolicyDocument, error) {
|
||||
store := cspm.credentialManager.GetStore()
|
||||
|
||||
if policyStore, ok := store.(credential.PolicyManager); ok {
|
||||
return policyStore.GetPolicy(ctx, name)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("credential store doesn't support policy retrieval")
|
||||
return cspm.credentialManager.GetPolicy(ctx, name)
|
||||
}
|
||||
|
||||
// AdminServer policy management methods using credential.PolicyManager
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
)
|
||||
|
||||
// identityToServiceAccount converts an IAM identity to a ServiceAccount struct
|
||||
// This helper reduces code duplication across GetServiceAccounts, GetServiceAccountDetails,
|
||||
// UpdateServiceAccount, and GetServiceAccountByAccessKey
|
||||
func identityToServiceAccount(identity *iam_pb.Identity) (*ServiceAccount, error) {
|
||||
if identity == nil {
|
||||
return nil, fmt.Errorf("identity cannot be nil")
|
||||
}
|
||||
if !strings.HasPrefix(identity.GetName(), serviceAccountPrefix) {
|
||||
return nil, fmt.Errorf("not a service account: %s", identity.GetName())
|
||||
}
|
||||
|
||||
parts := strings.SplitN(identity.GetName(), ":", 3)
|
||||
if len(parts) < 3 {
|
||||
return nil, fmt.Errorf("invalid service account ID format")
|
||||
}
|
||||
|
||||
sa := &ServiceAccount{
|
||||
ID: identity.GetName(),
|
||||
ParentUser: parts[1],
|
||||
Status: StatusActive,
|
||||
CreateDate: getCreationDate(identity.GetActions()),
|
||||
Expiration: getExpiration(identity.GetActions()),
|
||||
}
|
||||
|
||||
// Get description from account display name
|
||||
if identity.Account != nil {
|
||||
sa.Description = identity.Account.GetDisplayName()
|
||||
}
|
||||
|
||||
// Get access key from credentials
|
||||
if len(identity.Credentials) > 0 {
|
||||
sa.AccessKeyId = identity.Credentials[0].GetAccessKey()
|
||||
}
|
||||
|
||||
// Check if disabled
|
||||
for _, action := range identity.GetActions() {
|
||||
if action == disabledAction {
|
||||
sa.Status = StatusInactive
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return sa, nil
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -18,140 +17,57 @@ var (
|
||||
)
|
||||
|
||||
const (
|
||||
createdAtActionPrefix = "createdAt:"
|
||||
expirationActionPrefix = "expiresAt:"
|
||||
disabledAction = "__disabled__"
|
||||
serviceAccountPrefix = "sa:"
|
||||
accessKeyPrefix = "ABIA" // Service account access keys use ABIA prefix
|
||||
serviceAccountPrefix = "sa:"
|
||||
accessKeyPrefix = "ABIA" // Service account access keys use ABIA prefix
|
||||
|
||||
// Status constants
|
||||
StatusActive = "Active"
|
||||
StatusInactive = "Inactive"
|
||||
)
|
||||
|
||||
// Helper functions for managing creation timestamps in actions
|
||||
func getCreationDate(actions []string) time.Time {
|
||||
for _, action := range actions {
|
||||
if strings.HasPrefix(action, createdAtActionPrefix) {
|
||||
timestampStr := strings.TrimPrefix(action, createdAtActionPrefix)
|
||||
if timestamp, err := strconv.ParseInt(timestampStr, 10, 64); err == nil {
|
||||
return time.Unix(timestamp, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
return time.Time{} // Return zero time for legacy service accounts without stored creation date
|
||||
}
|
||||
|
||||
func setCreationDate(actions []string, createDate time.Time) []string {
|
||||
// Remove any existing createdAt action
|
||||
filtered := make([]string, 0, len(actions)+1)
|
||||
for _, action := range actions {
|
||||
if !strings.HasPrefix(action, createdAtActionPrefix) {
|
||||
filtered = append(filtered, action)
|
||||
}
|
||||
}
|
||||
// Add new createdAt action
|
||||
filtered = append(filtered, fmt.Sprintf("%s%d", createdAtActionPrefix, createDate.Unix()))
|
||||
return filtered
|
||||
}
|
||||
|
||||
// Helper functions for managing expiration timestamps in actions
|
||||
func getExpiration(actions []string) time.Time {
|
||||
for _, action := range actions {
|
||||
if strings.HasPrefix(action, expirationActionPrefix) {
|
||||
timestampStr := strings.TrimPrefix(action, expirationActionPrefix)
|
||||
if timestamp, err := strconv.ParseInt(timestampStr, 10, 64); err == nil {
|
||||
return time.Unix(timestamp, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
return time.Time{} // No expiration set
|
||||
}
|
||||
|
||||
func setExpiration(actions []string, expiration time.Time) []string {
|
||||
// Remove any existing expiration action
|
||||
filtered := make([]string, 0, len(actions)+1)
|
||||
for _, action := range actions {
|
||||
if !strings.HasPrefix(action, expirationActionPrefix) {
|
||||
filtered = append(filtered, action)
|
||||
}
|
||||
}
|
||||
// Add new expiration action if not zero
|
||||
if !expiration.IsZero() {
|
||||
filtered = append(filtered, fmt.Sprintf("%s%d", expirationActionPrefix, expiration.Unix()))
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
// GetServiceAccounts returns all service accounts, optionally filtered by parent user
|
||||
// NOTE: Service accounts are stored as special identities with "sa:" prefix
|
||||
func (s *AdminServer) GetServiceAccounts(ctx context.Context, parentUser string) ([]ServiceAccount, error) {
|
||||
if s.credentialManager == nil {
|
||||
return nil, fmt.Errorf("credential manager not available")
|
||||
}
|
||||
|
||||
// Load the current configuration to find service account identities
|
||||
config, err := s.credentialManager.LoadConfiguration(ctx)
|
||||
pbAccounts, err := s.credentialManager.ListServiceAccounts(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load configuration: %w", err)
|
||||
return nil, fmt.Errorf("failed to list service accounts: %w", err)
|
||||
}
|
||||
|
||||
var accounts []ServiceAccount
|
||||
|
||||
// Service accounts are stored as identities with "sa:" prefix in their name
|
||||
// Format: "sa:<parent_user>:<uuid>"
|
||||
for _, identity := range config.GetIdentities() {
|
||||
if !strings.HasPrefix(identity.GetName(), serviceAccountPrefix) {
|
||||
for _, sa := range pbAccounts {
|
||||
if sa == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
parts := strings.SplitN(identity.GetName(), ":", 3)
|
||||
if len(parts) < 3 {
|
||||
continue
|
||||
}
|
||||
|
||||
parent := parts[1]
|
||||
saId := identity.GetName()
|
||||
|
||||
// Filter by parent user if specified
|
||||
if parentUser != "" && parent != parentUser {
|
||||
if parentUser != "" && sa.ParentUser != parentUser {
|
||||
continue
|
||||
}
|
||||
|
||||
// Extract description from account display name if available
|
||||
description := ""
|
||||
status := StatusActive
|
||||
if identity.Account != nil {
|
||||
description = identity.Account.GetDisplayName()
|
||||
if sa.Disabled {
|
||||
status = StatusInactive
|
||||
}
|
||||
|
||||
// Get access key from credentials
|
||||
accessKey := ""
|
||||
if len(identity.Credentials) > 0 {
|
||||
accessKey = identity.Credentials[0].GetAccessKey()
|
||||
// Service accounts use ABIA prefix
|
||||
if !strings.HasPrefix(accessKey, accessKeyPrefix) {
|
||||
continue // Not a service account
|
||||
}
|
||||
}
|
||||
|
||||
// Check if disabled (stored in actions)
|
||||
for _, action := range identity.GetActions() {
|
||||
if action == disabledAction {
|
||||
status = StatusInactive
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
accounts = append(accounts, ServiceAccount{
|
||||
ID: saId,
|
||||
ParentUser: parent,
|
||||
Description: description,
|
||||
AccessKeyId: accessKey,
|
||||
account := ServiceAccount{
|
||||
ID: sa.Id,
|
||||
ParentUser: sa.ParentUser,
|
||||
Description: sa.Description,
|
||||
Status: status,
|
||||
CreateDate: getCreationDate(identity.GetActions()),
|
||||
Expiration: getExpiration(identity.GetActions()),
|
||||
})
|
||||
CreateDate: time.Unix(sa.CreatedAt, 0),
|
||||
}
|
||||
|
||||
if sa.Expiration > 0 {
|
||||
account.Expiration = time.Unix(sa.Expiration, 0)
|
||||
}
|
||||
|
||||
if sa.Credential != nil {
|
||||
account.AccessKeyId = sa.Credential.AccessKey
|
||||
}
|
||||
|
||||
accounts = append(accounts, account)
|
||||
}
|
||||
|
||||
return accounts, nil
|
||||
@@ -163,43 +79,33 @@ func (s *AdminServer) GetServiceAccountDetails(ctx context.Context, id string) (
|
||||
return nil, fmt.Errorf("credential manager not available")
|
||||
}
|
||||
|
||||
// Get the identity
|
||||
identity, err := s.credentialManager.GetUser(ctx, id)
|
||||
sa, err := s.credentialManager.GetServiceAccount(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %s", ErrServiceAccountNotFound, id)
|
||||
return nil, fmt.Errorf("failed to get service account: %w", err)
|
||||
}
|
||||
if sa == nil {
|
||||
return nil, ErrServiceAccountNotFound
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(identity.GetName(), serviceAccountPrefix) {
|
||||
return nil, fmt.Errorf("%w: not a service account: %s", ErrServiceAccountNotFound, id)
|
||||
}
|
||||
|
||||
parts := strings.SplitN(identity.GetName(), ":", 3)
|
||||
if len(parts) < 3 {
|
||||
return nil, fmt.Errorf("invalid service account ID format")
|
||||
status := StatusActive
|
||||
if sa.Disabled {
|
||||
status = StatusInactive
|
||||
}
|
||||
|
||||
account := &ServiceAccount{
|
||||
ID: id,
|
||||
ParentUser: parts[1],
|
||||
Status: StatusActive,
|
||||
CreateDate: getCreationDate(identity.GetActions()),
|
||||
Expiration: getExpiration(identity.GetActions()),
|
||||
ID: sa.Id,
|
||||
ParentUser: sa.ParentUser,
|
||||
Description: sa.Description,
|
||||
Status: status,
|
||||
CreateDate: time.Unix(sa.CreatedAt, 0),
|
||||
}
|
||||
|
||||
if identity.Account != nil {
|
||||
account.Description = identity.Account.GetDisplayName()
|
||||
if sa.Expiration > 0 {
|
||||
account.Expiration = time.Unix(sa.Expiration, 0)
|
||||
}
|
||||
|
||||
if len(identity.Credentials) > 0 {
|
||||
account.AccessKeyId = identity.Credentials[0].GetAccessKey()
|
||||
}
|
||||
|
||||
// Check if disabled
|
||||
for _, action := range identity.GetActions() {
|
||||
if action == disabledAction {
|
||||
account.Status = StatusInactive
|
||||
break
|
||||
}
|
||||
if sa.Credential != nil {
|
||||
account.AccessKeyId = sa.Credential.AccessKey
|
||||
}
|
||||
|
||||
return account, nil
|
||||
@@ -212,55 +118,48 @@ func (s *AdminServer) CreateServiceAccount(ctx context.Context, req CreateServic
|
||||
}
|
||||
|
||||
// Validate parent user exists
|
||||
_, err := s.credentialManager.GetUser(ctx, req.ParentUser)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parent user not found: %s", req.ParentUser)
|
||||
if _, err := s.credentialManager.GetUser(ctx, req.ParentUser); err != nil {
|
||||
return nil, fmt.Errorf("parent user lookup failed for %s: %w", req.ParentUser, err)
|
||||
}
|
||||
|
||||
// Generate unique ID and credentials
|
||||
uuid := generateAccountId()
|
||||
// Maintain consistent ID format: sa:<parent>:<uuid>
|
||||
saId := fmt.Sprintf("sa:%s:%s", req.ParentUser, uuid)
|
||||
accessKey := accessKeyPrefix + generateAccessKey()[len(accessKeyPrefix):] // Use ABIA prefix for service accounts
|
||||
|
||||
accessKey := accessKeyPrefix + generateAccessKey()[len(accessKeyPrefix):]
|
||||
secretKey := generateSecretKey()
|
||||
|
||||
// Create the service account as a special identity
|
||||
now := time.Now()
|
||||
|
||||
// Parse expiration if provided
|
||||
var expiration time.Time
|
||||
sa := &iam_pb.ServiceAccount{
|
||||
Id: saId,
|
||||
ParentUser: req.ParentUser,
|
||||
Description: req.Description,
|
||||
Credential: &iam_pb.Credential{
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
Status: StatusActive,
|
||||
},
|
||||
CreatedAt: now.Unix(),
|
||||
Disabled: false,
|
||||
}
|
||||
|
||||
if req.Expiration != "" {
|
||||
var err error
|
||||
expiration, err = time.Parse(time.RFC3339, req.Expiration)
|
||||
exp, err := time.Parse(time.RFC3339, req.Expiration)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid expiration format: %w", err)
|
||||
}
|
||||
sa.Expiration = exp.Unix()
|
||||
}
|
||||
|
||||
identity := &iam_pb.Identity{
|
||||
Name: saId,
|
||||
Account: &iam_pb.Account{
|
||||
Id: uuid,
|
||||
DisplayName: req.Description,
|
||||
},
|
||||
Credentials: []*iam_pb.Credential{
|
||||
{
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
},
|
||||
},
|
||||
// Store creation date and expiration in actions
|
||||
Actions: setExpiration(setCreationDate([]string{}, now), expiration),
|
||||
}
|
||||
|
||||
// Create the service account
|
||||
err = s.credentialManager.CreateUser(ctx, identity)
|
||||
if err != nil {
|
||||
if err := s.credentialManager.CreateServiceAccount(ctx, sa); err != nil {
|
||||
return nil, fmt.Errorf("failed to create service account: %w", err)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Created service account %s for user %s", saId, req.ParentUser)
|
||||
|
||||
return &ServiceAccount{
|
||||
resp := &ServiceAccount{
|
||||
ID: saId,
|
||||
ParentUser: req.ParentUser,
|
||||
Description: req.Description,
|
||||
@@ -268,8 +167,13 @@ func (s *AdminServer) CreateServiceAccount(ctx context.Context, req CreateServic
|
||||
SecretAccessKey: secretKey, // Only returned on creation
|
||||
Status: StatusActive,
|
||||
CreateDate: now,
|
||||
Expiration: expiration,
|
||||
}, nil
|
||||
}
|
||||
|
||||
if sa.Expiration > 0 {
|
||||
resp.Expiration = time.Unix(sa.Expiration, 0)
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// UpdateServiceAccount updates an existing service account
|
||||
@@ -278,85 +182,67 @@ func (s *AdminServer) UpdateServiceAccount(ctx context.Context, id string, req U
|
||||
return nil, fmt.Errorf("credential manager not available")
|
||||
}
|
||||
|
||||
// Get existing identity
|
||||
identity, err := s.credentialManager.GetUser(ctx, id)
|
||||
sa, err := s.credentialManager.GetServiceAccount(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %s", ErrServiceAccountNotFound, id)
|
||||
return nil, fmt.Errorf("failed to get service account: %w", err)
|
||||
}
|
||||
if sa == nil {
|
||||
return nil, ErrServiceAccountNotFound
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(identity.GetName(), serviceAccountPrefix) {
|
||||
return nil, fmt.Errorf("%w: not a service account: %s", ErrServiceAccountNotFound, id)
|
||||
}
|
||||
|
||||
// Update description if provided
|
||||
if req.Description != "" {
|
||||
if identity.Account == nil {
|
||||
identity.Account = &iam_pb.Account{}
|
||||
}
|
||||
identity.Account.DisplayName = req.Description
|
||||
sa.Description = req.Description
|
||||
}
|
||||
|
||||
// Update status by adding/removing disabled action
|
||||
if req.Status != "" {
|
||||
// Remove existing disabled marker
|
||||
newActions := make([]string, 0, len(identity.Actions))
|
||||
for _, action := range identity.Actions {
|
||||
if action != disabledAction {
|
||||
newActions = append(newActions, action)
|
||||
}
|
||||
switch req.Status {
|
||||
case StatusInactive:
|
||||
sa.Disabled = true
|
||||
case StatusActive:
|
||||
sa.Disabled = false
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid status value: %s (must be %s or %s)", req.Status, StatusActive, StatusInactive)
|
||||
}
|
||||
// Add disabled action if setting to Inactive
|
||||
if req.Status == StatusInactive {
|
||||
newActions = append(newActions, disabledAction)
|
||||
}
|
||||
identity.Actions = newActions
|
||||
}
|
||||
|
||||
// Update expiration if provided
|
||||
if req.Expiration != "" {
|
||||
var expiration time.Time
|
||||
var err error
|
||||
expiration, err = time.Parse(time.RFC3339, req.Expiration)
|
||||
exp, err := time.Parse(time.RFC3339, req.Expiration)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid expiration format: %w", err)
|
||||
}
|
||||
identity.Actions = setExpiration(identity.Actions, expiration)
|
||||
sa.Expiration = exp.Unix()
|
||||
}
|
||||
|
||||
// Update the identity
|
||||
err = s.credentialManager.UpdateUser(ctx, id, identity)
|
||||
if err != nil {
|
||||
if err := s.credentialManager.UpdateServiceAccount(ctx, id, sa); err != nil {
|
||||
return nil, fmt.Errorf("failed to update service account: %w", err)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Updated service account %s", id)
|
||||
|
||||
// Build response
|
||||
parts := strings.SplitN(id, ":", 3)
|
||||
if len(parts) < 3 {
|
||||
return nil, fmt.Errorf("invalid service account ID format")
|
||||
status := StatusActive
|
||||
if sa.Disabled {
|
||||
status = StatusInactive
|
||||
}
|
||||
|
||||
result := &ServiceAccount{
|
||||
ID: id,
|
||||
ParentUser: parts[1],
|
||||
Description: identity.Account.GetDisplayName(),
|
||||
Status: StatusActive,
|
||||
CreateDate: getCreationDate(identity.Actions),
|
||||
accessKeyId := ""
|
||||
if sa.Credential != nil {
|
||||
accessKeyId = sa.Credential.AccessKey
|
||||
}
|
||||
|
||||
if len(identity.Credentials) > 0 {
|
||||
result.AccessKeyId = identity.Credentials[0].GetAccessKey()
|
||||
resp := &ServiceAccount{
|
||||
ID: sa.Id,
|
||||
ParentUser: sa.ParentUser,
|
||||
Description: sa.Description,
|
||||
Status: status,
|
||||
CreateDate: time.Unix(sa.CreatedAt, 0),
|
||||
AccessKeyId: accessKeyId,
|
||||
}
|
||||
|
||||
for _, action := range identity.Actions {
|
||||
if action == disabledAction {
|
||||
result.Status = StatusInactive
|
||||
break
|
||||
}
|
||||
if sa.Expiration > 0 {
|
||||
resp.Expiration = time.Unix(sa.Expiration, 0)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// DeleteServiceAccount deletes a service account
|
||||
@@ -365,19 +251,16 @@ func (s *AdminServer) DeleteServiceAccount(ctx context.Context, id string) error
|
||||
return fmt.Errorf("credential manager not available")
|
||||
}
|
||||
|
||||
// Verify it's a service account
|
||||
identity, err := s.credentialManager.GetUser(ctx, id)
|
||||
// Verify existence
|
||||
sa, err := s.credentialManager.GetServiceAccount(ctx, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %s", ErrServiceAccountNotFound, id)
|
||||
return fmt.Errorf("failed to check service account: %w", err)
|
||||
}
|
||||
if sa == nil {
|
||||
return ErrServiceAccountNotFound
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(identity.GetName(), serviceAccountPrefix) {
|
||||
return fmt.Errorf("%w: not a service account: %s", ErrServiceAccountNotFound, id)
|
||||
}
|
||||
|
||||
// Delete the identity
|
||||
err = s.credentialManager.DeleteUser(ctx, id)
|
||||
if err != nil {
|
||||
if err := s.credentialManager.DeleteServiceAccount(ctx, id); err != nil {
|
||||
return fmt.Errorf("failed to delete service account: %w", err)
|
||||
}
|
||||
|
||||
@@ -395,40 +278,30 @@ func (s *AdminServer) GetServiceAccountByAccessKey(ctx context.Context, accessKe
|
||||
return nil, fmt.Errorf("credential manager not available")
|
||||
}
|
||||
|
||||
// Find identity by access key
|
||||
identity, err := s.credentialManager.GetUserByAccessKey(ctx, accessKey)
|
||||
// Efficient lookup is now supported by the interface and optimized stores
|
||||
sa, err := s.credentialManager.GetStore().GetServiceAccountByAccessKey(ctx, accessKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("service account not found for access key: %s", accessKey)
|
||||
return nil, fmt.Errorf("failed to find service account: %w", err)
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(identity.GetName(), serviceAccountPrefix) {
|
||||
return nil, fmt.Errorf("not a service account")
|
||||
status := StatusActive
|
||||
if sa.Disabled {
|
||||
status = StatusInactive
|
||||
}
|
||||
|
||||
parts := strings.SplitN(identity.GetName(), ":", 3)
|
||||
if len(parts) < 3 {
|
||||
return nil, fmt.Errorf("invalid service account ID format")
|
||||
accessKeyId := ""
|
||||
if sa.Credential != nil {
|
||||
accessKeyId = sa.Credential.AccessKey
|
||||
}
|
||||
|
||||
account := &ServiceAccount{
|
||||
ID: identity.GetName(),
|
||||
ParentUser: parts[1],
|
||||
AccessKeyId: accessKey,
|
||||
Status: StatusActive,
|
||||
CreateDate: getCreationDate(identity.GetActions()),
|
||||
Expiration: getExpiration(identity.GetActions()),
|
||||
resp := &ServiceAccount{
|
||||
ID: sa.Id,
|
||||
ParentUser: sa.ParentUser,
|
||||
Description: sa.Description,
|
||||
AccessKeyId: accessKeyId,
|
||||
Status: status,
|
||||
CreateDate: time.Unix(sa.CreatedAt, 0),
|
||||
}
|
||||
|
||||
if identity.Account != nil {
|
||||
account.Description = identity.Account.GetDisplayName()
|
||||
if sa.Expiration > 0 {
|
||||
resp.Expiration = time.Unix(sa.Expiration, 0)
|
||||
}
|
||||
|
||||
for _, action := range identity.GetActions() {
|
||||
if action == disabledAction {
|
||||
account.Status = StatusInactive
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return account, nil
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user