Browse Source
migrate IAM policies to multi-file storage (#8114)
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.pull/8128/head
committed by
GitHub
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
59 changed files with 2886 additions and 1388 deletions
-
59weed/admin/dash/policies_management.go
-
53weed/admin/dash/service_account_helpers.go
-
373weed/admin/dash/service_account_management.go
-
6weed/admin/static/css/bootstrap.min.css
-
1weed/admin/static/css/bootstrap.min.css.map
-
6weed/admin/static/js/bootstrap.bundle.min.js
-
1weed/admin/static/js/bootstrap.bundle.min.js.map
-
55weed/admin/static/js/iam-utils.js
-
331weed/admin/static/js/modal-alerts.js
-
58weed/admin/view/app/cluster_ec_shards.templ
-
126weed/admin/view/app/cluster_ec_shards_templ.go
-
10weed/admin/view/app/cluster_ec_volumes.templ
-
2weed/admin/view/app/cluster_ec_volumes_templ.go
-
8weed/admin/view/app/collection_details.templ
-
2weed/admin/view/app/collection_details_templ.go
-
9weed/admin/view/app/file_browser.templ
-
2weed/admin/view/app/file_browser_templ.go
-
4weed/admin/view/app/maintenance_config.templ
-
22weed/admin/view/app/maintenance_config_schema.templ
-
50weed/admin/view/app/maintenance_config_schema_templ.go
-
2weed/admin/view/app/maintenance_config_templ.go
-
19weed/admin/view/app/maintenance_workers.templ
-
2weed/admin/view/app/maintenance_workers_templ.go
-
103weed/admin/view/app/object_store_users.templ
-
2weed/admin/view/app/object_store_users_templ.go
-
44weed/admin/view/app/policies.templ
-
2weed/admin/view/app/policies_templ.go
-
13weed/admin/view/app/service_accounts.templ
-
2weed/admin/view/app/service_accounts_templ.go
-
4weed/admin/view/app/task_config.templ
-
4weed/admin/view/app/task_config_schema.templ
-
2weed/admin/view/app/task_config_schema_templ.go
-
2weed/admin/view/app/task_config_templ.go
-
4weed/admin/view/app/task_config_templ.templ
-
2weed/admin/view/app/task_config_templ_templ.go
-
20weed/admin/view/app/task_detail.templ
-
2weed/admin/view/app/task_detail_templ.go
-
3weed/admin/view/layout/layout.templ
-
8weed/admin/view/layout/layout_templ.go
-
1weed/command/imports.go
-
5weed/command/scaffold/credential.toml
-
45weed/credential/credential_manager.go
-
24weed/credential/credential_store.go
-
210weed/credential/filer_etc/filer_etc_identity.go
-
224weed/credential/filer_etc/filer_etc_policy.go
-
206weed/credential/filer_etc/filer_etc_service_account.go
-
498weed/credential/filer_multiple/filer_multiple_store.go
-
16weed/credential/grpc/grpc_policy.go
-
78weed/credential/grpc/grpc_service_account.go
-
85weed/credential/memory/memory_service_account.go
-
29weed/credential/memory/memory_store.go
-
65weed/credential/memory/memory_store_test.go
-
173weed/credential/postgres/postgres_service_account.go
-
15weed/credential/postgres/postgres_store.go
-
28weed/credential/validation.go
-
56weed/pb/iam.proto
-
703weed/pb/iam_pb/iam.pb.go
-
258weed/pb/iam_pb/iam_grpc.pb.go
-
137weed/server/filer_server_handlers_iam_grpc.go
@ -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 |
|||
} |
|||
6
weed/admin/static/css/bootstrap.min.css
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
1
weed/admin/static/css/bootstrap.min.css.map
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
6
weed/admin/static/js/bootstrap.bundle.min.js
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
1
weed/admin/static/js/bootstrap.bundle.min.js.map
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
@ -0,0 +1,55 @@ |
|||
/** |
|||
* Shared IAM utility functions for the SeaweedFS Admin Dashboard. |
|||
*/ |
|||
|
|||
// Delete user function
|
|||
async function deleteUser(username) { |
|||
showDeleteConfirm(username, async function () { |
|||
try { |
|||
const encodedUsername = encodeURIComponent(username); |
|||
const response = await fetch(`/api/users/${encodedUsername}`, { |
|||
method: 'DELETE' |
|||
}); |
|||
|
|||
if (response.ok) { |
|||
showAlert('User deleted successfully', 'success'); |
|||
setTimeout(() => window.location.reload(), 1000); |
|||
} else { |
|||
const error = await response.json().catch(() => ({})); |
|||
showAlert('Failed to delete user: ' + (error.error || 'Unknown error'), 'error'); |
|||
} |
|||
} catch (error) { |
|||
console.error('Error deleting user:', error); |
|||
showAlert('Failed to delete user: ' + error.message, 'error'); |
|||
} |
|||
}, 'Are you sure you want to delete this user? This action cannot be undone.'); |
|||
} |
|||
|
|||
// Delete access key function
|
|||
async function deleteAccessKey(username, accessKey) { |
|||
showDeleteConfirm(accessKey, async function () { |
|||
try { |
|||
const encodedUsername = encodeURIComponent(username); |
|||
const encodedAccessKey = encodeURIComponent(accessKey); |
|||
const response = await fetch(`/api/users/${encodedUsername}/access-keys/${encodedAccessKey}`, { |
|||
method: 'DELETE' |
|||
}); |
|||
|
|||
if (response.ok) { |
|||
showAlert('Access key deleted successfully', 'success'); |
|||
// If refreshAccessKeysList exists (in object_store_users.templ), use it
|
|||
if (typeof refreshAccessKeysList === 'function') { |
|||
refreshAccessKeysList(username); |
|||
} else { |
|||
setTimeout(() => window.location.reload(), 1000); |
|||
} |
|||
} else { |
|||
const error = await response.json().catch(() => ({})); |
|||
showAlert('Failed to delete access key: ' + (error.error || 'Unknown error'), 'error'); |
|||
} |
|||
} catch (error) { |
|||
console.error('Error deleting access key:', error); |
|||
showAlert('Failed to delete access key: ' + error.message, 'error'); |
|||
} |
|||
}, 'Are you sure you want to delete this access key?'); |
|||
} |
|||
@ -0,0 +1,331 @@ |
|||
/** |
|||
* Modal Alerts - Bootstrap Modal replacement for native alert() and confirm() |
|||
* Fixes Chrome auto-dismiss issue with native dialogs |
|||
* |
|||
* Usage: |
|||
* showAlert('Message', 'success'); |
|||
* showConfirm('Delete this?', function() { }); |
|||
*/ |
|||
|
|||
(function () { |
|||
'use strict'; |
|||
|
|||
// Create and inject modal HTML into page if not already present
|
|||
function ensureModalsExist() { |
|||
if (document.getElementById('globalAlertModal')) { |
|||
return; // Already exists
|
|||
} |
|||
|
|||
const modalsHTML = `
|
|||
<!-- Global Alert Modal --> |
|||
<div class="modal fade" id="globalAlertModal" tabindex="-1" aria-labelledby="globalAlertModalLabel" aria-hidden="true"> |
|||
<div class="modal-dialog"> |
|||
<div class="modal-content"> |
|||
<div class="modal-header" id="globalAlertModalHeader"> |
|||
<h5 class="modal-title" id="globalAlertModalLabel"> |
|||
<i class="fas fa-info-circle me-2" id="globalAlertModalIcon"></i> |
|||
<span id="globalAlertModalTitle">Notice</span> |
|||
</h5> |
|||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> |
|||
</div> |
|||
<div class="modal-body" id="globalAlertModalBody"> |
|||
<!-- Message will be inserted here --> |
|||
</div> |
|||
<div class="modal-footer"> |
|||
<button type="button" class="btn btn-primary" data-bs-dismiss="modal">OK</button> |
|||
</div> |
|||
</div> |
|||
</div> |
|||
</div> |
|||
|
|||
<!-- Global Confirm Modal --> |
|||
<div class="modal fade" id="globalConfirmModal" tabindex="-1" aria-labelledby="globalConfirmModalLabel" aria-hidden="true"> |
|||
<div class="modal-dialog"> |
|||
<div class="modal-content"> |
|||
<div class="modal-header bg-warning"> |
|||
<h5 class="modal-title" id="globalConfirmModalLabel"> |
|||
<i class="fas fa-question-circle me-2"></i><span id="globalConfirmModalTitleText">Confirm Action</span> |
|||
</h5> |
|||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> |
|||
</div> |
|||
<div class="modal-body" id="globalConfirmModalBody"> |
|||
<!-- Message will be inserted here --> |
|||
</div> |
|||
<div class="modal-footer"> |
|||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="globalConfirmCancelBtn">Cancel</button> |
|||
<button type="button" class="btn btn-primary" id="globalConfirmOkBtn">OK</button> |
|||
</div> |
|||
</div> |
|||
</div> |
|||
</div> |
|||
|
|||
<!-- Global Delete Confirm Modal --> |
|||
<div class="modal fade" id="globalDeleteModal" tabindex="-1" aria-labelledby="globalDeleteModalLabel" aria-hidden="true"> |
|||
<div class="modal-dialog"> |
|||
<div class="modal-content"> |
|||
<div class="modal-header bg-danger text-white"> |
|||
<h5 class="modal-title" id="globalDeleteModalLabel"> |
|||
<i class="fas fa-exclamation-triangle me-2"></i>Confirm Delete |
|||
</h5> |
|||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button> |
|||
</div> |
|||
<div class="modal-body"> |
|||
<p class="mb-2" id="globalDeleteModalMessage">Are you sure you want to delete this item?</p> |
|||
<p class="mb-0"><strong id="globalDeleteModalItemName"></strong></p> |
|||
<p class="text-muted small mt-2 mb-0">This action cannot be undone.</p> |
|||
</div> |
|||
<div class="modal-footer"> |
|||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> |
|||
<button type="button" class="btn btn-danger" id="globalDeleteConfirmBtn"> |
|||
<i class="fas fa-trash me-1"></i>Delete |
|||
</button> |
|||
</div> |
|||
</div> |
|||
</div> |
|||
</div> |
|||
`;
|
|||
|
|||
// Inject modals at end of body
|
|||
document.body.insertAdjacentHTML('beforeend', modalsHTML); |
|||
} |
|||
|
|||
/** |
|||
* Show an alert message using Bootstrap modal |
|||
* @param {string} message - The message to display |
|||
* @param {string|object} typeOrOptions - Type ('success', 'error', 'warning', 'info') or options object |
|||
* @param {string} title - Optional custom title |
|||
*/ |
|||
window.showAlert = function (message, typeOrOptions, title) { |
|||
ensureModalsExist(); |
|||
|
|||
let type = 'info'; |
|||
let isHtml = false; |
|||
|
|||
if (typeof typeOrOptions === 'object' && typeOrOptions !== null) { |
|||
type = typeOrOptions.type || 'info'; |
|||
isHtml = typeOrOptions.isHtml || false; |
|||
title = typeOrOptions.title || title; |
|||
} else if (typeof typeOrOptions === 'string') { |
|||
type = typeOrOptions; |
|||
} |
|||
|
|||
const modal = document.getElementById('globalAlertModal'); |
|||
const header = document.getElementById('globalAlertModalHeader'); |
|||
const titleEl = document.getElementById('globalAlertModalTitle'); |
|||
const bodyEl = document.getElementById('globalAlertModalBody'); |
|||
const iconEl = document.getElementById('globalAlertModalIcon'); |
|||
|
|||
// Configuration for different types
|
|||
const types = { |
|||
'success': { |
|||
title: 'Success', |
|||
icon: 'fa-check-circle', |
|||
headerClass: 'bg-success text-white', |
|||
btnClose: 'btn-close-white' |
|||
}, |
|||
'error': { |
|||
title: 'Error', |
|||
icon: 'fa-exclamation-triangle', |
|||
headerClass: 'bg-danger text-white', |
|||
btnClose: 'btn-close-white' |
|||
}, |
|||
'warning': { |
|||
title: 'Warning', |
|||
icon: 'fa-exclamation-circle', |
|||
headerClass: 'bg-warning text-dark', |
|||
btnClose: '' |
|||
}, |
|||
'info': { |
|||
title: 'Notice', |
|||
icon: 'fa-info-circle', |
|||
headerClass: 'bg-info text-white', |
|||
btnClose: 'btn-close-white' |
|||
} |
|||
}; |
|||
|
|||
const config = types[type] || types['info']; |
|||
|
|||
// Update header styling
|
|||
header.className = 'modal-header ' + config.headerClass; |
|||
const closeBtn = header.querySelector('.btn-close'); |
|||
closeBtn.className = 'btn-close ' + config.btnClose; |
|||
|
|||
// Update icon
|
|||
iconEl.className = 'fas ' + config.icon + ' me-2'; |
|||
|
|||
// Update title
|
|||
titleEl.textContent = title || config.title; |
|||
|
|||
// Update body - support HTML or text
|
|||
if (isHtml || message.includes('<p>') || message.includes('<ul>')) { |
|||
bodyEl.innerHTML = message; |
|||
} else { |
|||
bodyEl.innerHTML = '<p class="mb-0">' + escapeHtml(message) + '</p>'; |
|||
} |
|||
|
|||
// Show modal
|
|||
const bsModal = new bootstrap.Modal(modal); |
|||
bsModal.show(); |
|||
}; |
|||
|
|||
/** |
|||
* Show a confirmation dialog using Bootstrap modal |
|||
* @param {string} message - The confirmation message |
|||
* @param {function} onConfirm - Callback function if user confirms |
|||
* @param {function|object} onCancelOrOptions - Optional callback or options object |
|||
* @param {string} title - Optional custom title |
|||
*/ |
|||
window.showConfirm = function (message, onConfirm, onCancelOrOptions, title) { |
|||
ensureModalsExist(); |
|||
|
|||
let onCancel = null; |
|||
let isHtml = false; |
|||
|
|||
if (typeof onCancelOrOptions === 'object' && onCancelOrOptions !== null) { |
|||
onCancel = onCancelOrOptions.onCancel; |
|||
isHtml = onCancelOrOptions.isHtml || false; |
|||
title = onCancelOrOptions.title || null; |
|||
} else { |
|||
onCancel = onCancelOrOptions; |
|||
} |
|||
|
|||
const modalEl = document.getElementById('globalConfirmModal'); |
|||
const bodyEl = document.getElementById('globalConfirmModalBody'); |
|||
const titleEl = document.getElementById('globalConfirmModalTitleText'); |
|||
const okBtn = document.getElementById('globalConfirmOkBtn'); |
|||
const cancelBtn = document.getElementById('globalConfirmCancelBtn'); |
|||
|
|||
// Set title
|
|||
if (title) { |
|||
titleEl.textContent = title; |
|||
} else { |
|||
titleEl.textContent = 'Confirm Action'; |
|||
} |
|||
|
|||
// Set message
|
|||
if (isHtml || message.includes('<p>') || message.includes('<ul>')) { |
|||
bodyEl.innerHTML = message; |
|||
} else { |
|||
bodyEl.innerHTML = '<p class="mb-0">' + escapeHtml(message) + '</p>'; |
|||
} |
|||
|
|||
// Remove old event listeners by cloning buttons
|
|||
const newOkBtn = okBtn.cloneNode(true); |
|||
const newCancelBtn = cancelBtn.cloneNode(true); |
|||
okBtn.parentNode.replaceChild(newOkBtn, okBtn); |
|||
cancelBtn.parentNode.replaceChild(newCancelBtn, cancelBtn); |
|||
|
|||
const modal = new bootstrap.Modal(modalEl); |
|||
|
|||
// Add event listeners
|
|||
newOkBtn.addEventListener('click', function () { |
|||
modal.hide(); |
|||
if (typeof onConfirm === 'function') { |
|||
onConfirm(); |
|||
} |
|||
}); |
|||
|
|||
newCancelBtn.addEventListener('click', function () { |
|||
modal.hide(); |
|||
if (typeof onCancel === 'function') { |
|||
onCancel(); |
|||
} |
|||
}); |
|||
|
|||
modal.show(); |
|||
}; |
|||
|
|||
/** |
|||
* Show a delete confirmation dialog |
|||
* @param {string} itemName - Name of the item to delete |
|||
* @param {function} onConfirm - Callback function if user confirms deletion |
|||
* @param {string} message - Optional custom message (default: "Are you sure you want to delete this item?") |
|||
*/ |
|||
window.showDeleteConfirm = function (itemName, onConfirm, message) { |
|||
ensureModalsExist(); |
|||
|
|||
const modalEl = document.getElementById('globalDeleteModal'); |
|||
const messageEl = document.getElementById('globalDeleteModalMessage'); |
|||
const itemNameEl = document.getElementById('globalDeleteModalItemName'); |
|||
const confirmBtn = document.getElementById('globalDeleteConfirmBtn'); |
|||
|
|||
// Set custom message if provided
|
|||
if (message) { |
|||
messageEl.textContent = message; |
|||
} else { |
|||
messageEl.textContent = 'Are you sure you want to delete this item?'; |
|||
} |
|||
|
|||
// Set item name
|
|||
itemNameEl.textContent = itemName; |
|||
|
|||
// Remove old event listener by cloning button
|
|||
const newConfirmBtn = confirmBtn.cloneNode(true); |
|||
confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn); |
|||
|
|||
const modal = new bootstrap.Modal(modalEl); |
|||
|
|||
// Add new event listener
|
|||
newConfirmBtn.addEventListener('click', function () { |
|||
modal.hide(); |
|||
if (typeof onConfirm === 'function') { |
|||
onConfirm(); |
|||
} |
|||
}); |
|||
|
|||
modal.show(); |
|||
}; |
|||
|
|||
/** |
|||
* Escape HTML to prevent XSS |
|||
*/ |
|||
function escapeHtml(text) { |
|||
const map = { |
|||
'&': '&', |
|||
'<': '<', |
|||
'>': '>', |
|||
'"': '"', |
|||
"'": ''' |
|||
}; |
|||
return text.replace(/[&<>"']/g, function (m) { return map[m]; }); |
|||
} |
|||
|
|||
// Auto-initialize on DOMContentLoaded
|
|||
if (document.readyState === 'loading') { |
|||
document.addEventListener('DOMContentLoaded', ensureModalsExist); |
|||
} else { |
|||
ensureModalsExist(); |
|||
} |
|||
|
|||
/** |
|||
* AUTOMATIC OVERRIDE of native alert() |
|||
* This makes ALL existing alert() calls automatically use Bootstrap modals |
|||
*/ |
|||
window.alert = function (message) { |
|||
// Auto-detect message type from content
|
|||
let type = 'info'; |
|||
const msg = String(message || ''); |
|||
const msgLower = msg.toLowerCase(); |
|||
|
|||
// Refined type inference to avoid false positives
|
|||
if (msgLower.includes('success') || msgLower.includes('successfully') || msgLower.includes('created') || msgLower.includes('updated') || msgLower.includes('saved')) { |
|||
// Avoid "not successful"
|
|||
if (!msgLower.includes('not success')) { |
|||
type = 'success'; |
|||
} |
|||
} |
|||
|
|||
if (type === 'info') { |
|||
if (msgLower.includes('error') || msgLower.includes('failed') || msgLower.includes('invalid') || msgLower.includes('exception')) { |
|||
type = 'error'; |
|||
} else if (msgLower.includes('warning') || msgLower.includes('required') || msgLower.includes('attention')) { |
|||
type = 'warning'; |
|||
} |
|||
} |
|||
|
|||
showAlert(msg, type); |
|||
}; |
|||
|
|||
console.log('Modal Alerts library loaded - native alert() overridden'); |
|||
console.log('For confirm(), use showConfirm() or showDeleteConfirm() instead of native confirm()'); |
|||
})(); |
|||
2
weed/admin/view/app/file_browser_templ.go
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
50
weed/admin/view/app/maintenance_config_schema_templ.go
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
2
weed/admin/view/app/maintenance_workers_templ.go
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
2
weed/admin/view/app/object_store_users_templ.go
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
2
weed/admin/view/app/policies_templ.go
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
2
weed/admin/view/app/service_accounts_templ.go
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
2
weed/admin/view/app/task_detail_templ.go
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
@ -0,0 +1,206 @@ |
|||
package filer_etc |
|||
|
|||
import ( |
|||
"context" |
|||
"encoding/json" |
|||
"errors" |
|||
"fmt" |
|||
"strings" |
|||
|
|||
"github.com/seaweedfs/seaweedfs/weed/credential" |
|||
"github.com/seaweedfs/seaweedfs/weed/filer" |
|||
"github.com/seaweedfs/seaweedfs/weed/glog" |
|||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" |
|||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" |
|||
) |
|||
|
|||
func validateServiceAccountId(id string) error { |
|||
return credential.ValidateServiceAccountId(id) |
|||
} |
|||
|
|||
func (store *FilerEtcStore) loadServiceAccountsFromMultiFile(ctx context.Context, s3cfg *iam_pb.S3ApiConfiguration) error { |
|||
return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
dir := filer.IamConfigDirectory + "/" + IamServiceAccountsDirectory |
|||
entries, err := listEntries(ctx, client, dir) |
|||
if err != nil { |
|||
if err == filer_pb.ErrNotFound { |
|||
return nil |
|||
} |
|||
return err |
|||
} |
|||
|
|||
for _, entry := range entries { |
|||
if entry.IsDirectory { |
|||
continue |
|||
} |
|||
|
|||
var content []byte |
|||
if len(entry.Content) > 0 { |
|||
content = entry.Content |
|||
} else { |
|||
c, err := filer.ReadInsideFiler(client, dir, entry.Name) |
|||
if err != nil { |
|||
glog.Warningf("Failed to read service account file %s: %v", entry.Name, err) |
|||
continue |
|||
} |
|||
content = c |
|||
} |
|||
|
|||
if len(content) > 0 { |
|||
sa := &iam_pb.ServiceAccount{} |
|||
if err := json.Unmarshal(content, sa); err != nil { |
|||
glog.Warningf("Failed to unmarshal service account %s: %v", entry.Name, err) |
|||
continue |
|||
} |
|||
s3cfg.ServiceAccounts = append(s3cfg.ServiceAccounts, sa) |
|||
} |
|||
} |
|||
return nil |
|||
}) |
|||
} |
|||
|
|||
func (store *FilerEtcStore) saveServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) error { |
|||
if sa == nil { |
|||
return fmt.Errorf("service account is nil") |
|||
} |
|||
if err := validateServiceAccountId(sa.Id); err != nil { |
|||
return err |
|||
} |
|||
return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
data, err := json.Marshal(sa) |
|||
if err != nil { |
|||
return err |
|||
} |
|||
return filer.SaveInsideFiler(client, filer.IamConfigDirectory+"/"+IamServiceAccountsDirectory, sa.Id+".json", data) |
|||
}) |
|||
} |
|||
|
|||
func (store *FilerEtcStore) deleteServiceAccount(ctx context.Context, saId string) error { |
|||
if err := validateServiceAccountId(saId); err != nil { |
|||
return err |
|||
} |
|||
return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
resp, err := client.DeleteEntry(ctx, &filer_pb.DeleteEntryRequest{ |
|||
Directory: filer.IamConfigDirectory + "/" + IamServiceAccountsDirectory, |
|||
Name: saId + ".json", |
|||
}) |
|||
if err != nil { |
|||
if strings.Contains(err.Error(), filer_pb.ErrNotFound.Error()) { |
|||
return credential.ErrServiceAccountNotFound |
|||
} |
|||
return err |
|||
} |
|||
if resp != nil && resp.Error != "" { |
|||
if strings.Contains(resp.Error, filer_pb.ErrNotFound.Error()) { |
|||
return credential.ErrServiceAccountNotFound |
|||
} |
|||
return fmt.Errorf("delete service account %s: %s", saId, resp.Error) |
|||
} |
|||
return nil |
|||
}) |
|||
} |
|||
|
|||
func (store *FilerEtcStore) CreateServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) error { |
|||
existing, err := store.GetServiceAccount(ctx, sa.Id) |
|||
if err != nil { |
|||
if !errors.Is(err, credential.ErrServiceAccountNotFound) { |
|||
return err |
|||
} |
|||
} else if existing != nil { |
|||
return fmt.Errorf("service account %s already exists", sa.Id) |
|||
} |
|||
return store.saveServiceAccount(ctx, sa) |
|||
} |
|||
|
|||
func (store *FilerEtcStore) UpdateServiceAccount(ctx context.Context, id string, sa *iam_pb.ServiceAccount) error { |
|||
if sa.Id != id { |
|||
return fmt.Errorf("service account ID mismatch") |
|||
} |
|||
_, err := store.GetServiceAccount(ctx, id) |
|||
if err != nil { |
|||
return err |
|||
} |
|||
return store.saveServiceAccount(ctx, sa) |
|||
} |
|||
|
|||
func (store *FilerEtcStore) DeleteServiceAccount(ctx context.Context, id string) error { |
|||
return store.deleteServiceAccount(ctx, id) |
|||
} |
|||
|
|||
func (store *FilerEtcStore) GetServiceAccount(ctx context.Context, id string) (*iam_pb.ServiceAccount, error) { |
|||
if err := validateServiceAccountId(id); err != nil { |
|||
return nil, err |
|||
} |
|||
var sa *iam_pb.ServiceAccount |
|||
err := store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
data, err := filer.ReadInsideFiler(client, filer.IamConfigDirectory+"/"+IamServiceAccountsDirectory, id+".json") |
|||
if err != nil { |
|||
if err == filer_pb.ErrNotFound { |
|||
return credential.ErrServiceAccountNotFound |
|||
} |
|||
return err |
|||
} |
|||
if len(data) == 0 { |
|||
return credential.ErrServiceAccountNotFound |
|||
} |
|||
sa = &iam_pb.ServiceAccount{} |
|||
return json.Unmarshal(data, sa) |
|||
}) |
|||
return sa, err |
|||
} |
|||
|
|||
func (store *FilerEtcStore) ListServiceAccounts(ctx context.Context) ([]*iam_pb.ServiceAccount, error) { |
|||
var accounts []*iam_pb.ServiceAccount |
|||
err := store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
dir := filer.IamConfigDirectory + "/" + IamServiceAccountsDirectory |
|||
entries, err := listEntries(ctx, client, dir) |
|||
if err != nil { |
|||
if err == filer_pb.ErrNotFound { |
|||
return nil |
|||
} |
|||
return err |
|||
} |
|||
|
|||
for _, entry := range entries { |
|||
if entry.IsDirectory { |
|||
continue |
|||
} |
|||
|
|||
var content []byte |
|||
if len(entry.Content) > 0 { |
|||
content = entry.Content |
|||
} else { |
|||
c, err := filer.ReadInsideFiler(client, dir, entry.Name) |
|||
if err != nil { |
|||
glog.Warningf("Failed to read service account file %s: %v", entry.Name, err) |
|||
continue |
|||
} |
|||
content = c |
|||
} |
|||
|
|||
if len(content) > 0 { |
|||
sa := &iam_pb.ServiceAccount{} |
|||
if err := json.Unmarshal(content, sa); err != nil { |
|||
glog.Warningf("Failed to unmarshal service account %s: %v", entry.Name, err) |
|||
continue |
|||
} |
|||
accounts = append(accounts, sa) |
|||
} |
|||
} |
|||
return nil |
|||
}) |
|||
return accounts, err |
|||
} |
|||
|
|||
func (store *FilerEtcStore) GetServiceAccountByAccessKey(ctx context.Context, accessKey string) (*iam_pb.ServiceAccount, error) { |
|||
accounts, err := store.ListServiceAccounts(ctx) |
|||
if err != nil { |
|||
return nil, err |
|||
} |
|||
for _, sa := range accounts { |
|||
if sa.Credential != nil && sa.Credential.AccessKey == accessKey { |
|||
return sa, nil |
|||
} |
|||
} |
|||
return nil, credential.ErrAccessKeyNotFound |
|||
} |
|||
@ -1,498 +0,0 @@ |
|||
package filer_multiple |
|||
|
|||
import ( |
|||
"context" |
|||
"encoding/json" |
|||
"fmt" |
|||
"strings" |
|||
"sync" |
|||
|
|||
"github.com/seaweedfs/seaweedfs/weed/credential" |
|||
"github.com/seaweedfs/seaweedfs/weed/filer" |
|||
"github.com/seaweedfs/seaweedfs/weed/glog" |
|||
"github.com/seaweedfs/seaweedfs/weed/pb" |
|||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" |
|||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" |
|||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine" |
|||
"github.com/seaweedfs/seaweedfs/weed/util" |
|||
"google.golang.org/grpc" |
|||
) |
|||
|
|||
const ( |
|||
IdentitiesDirectory = "/etc/seaweedfs/identities" |
|||
PoliciesDirectory = "/etc/seaweedfs/policies" |
|||
) |
|||
|
|||
func init() { |
|||
credential.Stores = append(credential.Stores, &FilerMultipleStore{}) |
|||
} |
|||
|
|||
// FilerMultipleStore implements CredentialStore using SeaweedFS filer for storage
|
|||
// storing each identity in a separate file
|
|||
type FilerMultipleStore struct { |
|||
filerAddressFunc func() pb.ServerAddress // Function to get current active filer
|
|||
grpcDialOption grpc.DialOption |
|||
mu sync.RWMutex // Protects filerAddressFunc and grpcDialOption
|
|||
} |
|||
|
|||
func (store *FilerMultipleStore) GetName() credential.CredentialStoreTypeName { |
|||
return credential.StoreTypeFilerMultiple |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) Initialize(configuration util.Configuration, prefix string) error { |
|||
// Handle nil configuration gracefully
|
|||
if configuration != nil { |
|||
filerAddr := configuration.GetString(prefix + "filer") |
|||
if filerAddr != "" { |
|||
// Static configuration - use fixed address
|
|||
store.mu.Lock() |
|||
store.filerAddressFunc = func() pb.ServerAddress { |
|||
return pb.ServerAddress(filerAddr) |
|||
} |
|||
store.mu.Unlock() |
|||
} |
|||
} |
|||
// Note: filerAddressFunc can be set later via SetFilerAddressFunc method
|
|||
return nil |
|||
} |
|||
|
|||
// SetFilerAddressFunc sets a function that returns the current active filer address
|
|||
// This enables high availability by using the currently active filer
|
|||
func (store *FilerMultipleStore) SetFilerAddressFunc(getFiler func() pb.ServerAddress, grpcDialOption grpc.DialOption) { |
|||
store.mu.Lock() |
|||
defer store.mu.Unlock() |
|||
store.filerAddressFunc = getFiler |
|||
store.grpcDialOption = grpcDialOption |
|||
} |
|||
|
|||
// withFilerClient executes a function with a filer client
|
|||
func (store *FilerMultipleStore) withFilerClient(fn func(client filer_pb.SeaweedFilerClient) error) error { |
|||
store.mu.RLock() |
|||
if store.filerAddressFunc == nil { |
|||
store.mu.RUnlock() |
|||
return fmt.Errorf("filer_multiple: filer not yet available - please wait for filer discovery to complete and try again") |
|||
} |
|||
|
|||
filerAddress := store.filerAddressFunc() |
|||
dialOption := store.grpcDialOption |
|||
store.mu.RUnlock() |
|||
|
|||
if filerAddress == "" { |
|||
return fmt.Errorf("filer_multiple: no filer discovered yet - please ensure a filer is running and accessible") |
|||
} |
|||
|
|||
// Use the pb.WithGrpcFilerClient helper similar to existing code
|
|||
return pb.WithGrpcFilerClient(false, 0, filerAddress, dialOption, fn) |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) Shutdown() { |
|||
// No cleanup needed for file store
|
|||
} |
|||
|
|||
func (store *FilerMultipleStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3ApiConfiguration, error) { |
|||
s3cfg := &iam_pb.S3ApiConfiguration{} |
|||
|
|||
err := store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
// List and process all identity files in the directory using streaming callback
|
|||
return filer_pb.SeaweedList(ctx, client, IdentitiesDirectory, "", func(entry *filer_pb.Entry, isLast bool) error { |
|||
if entry.IsDirectory || !strings.HasSuffix(entry.Name, ".json") { |
|||
return nil |
|||
} |
|||
|
|||
content, err := filer.ReadInsideFiler(client, IdentitiesDirectory, entry.Name) |
|||
if err != nil { |
|||
glog.Warningf("Failed to read identity file %s: %v", entry.Name, err) |
|||
return nil // Continue with next file
|
|||
} |
|||
|
|||
identity := &iam_pb.Identity{} |
|||
if err := json.Unmarshal(content, identity); err != nil { |
|||
glog.Warningf("Failed to parse identity file %s: %v", entry.Name, err) |
|||
return nil // Continue with next file
|
|||
} |
|||
|
|||
s3cfg.Identities = append(s3cfg.Identities, identity) |
|||
return nil |
|||
}, "", false, 10000) |
|||
}) |
|||
|
|||
if err != nil { |
|||
// If listing failed because directory doesn't exist, treat as empty config
|
|||
if err == filer_pb.ErrNotFound { |
|||
return s3cfg, nil |
|||
} |
|||
return s3cfg, err |
|||
} |
|||
|
|||
return s3cfg, nil |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) SaveConfiguration(ctx context.Context, config *iam_pb.S3ApiConfiguration) error { |
|||
// This operation is expensive for multiple files mode as it would overwrite everything
|
|||
// But we implement it for interface compliance.
|
|||
// We will write each identity to a separate file and remove stale files.
|
|||
|
|||
return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
// 1. List existing identity files
|
|||
existingFileNames := make(map[string]bool) |
|||
err := filer_pb.SeaweedList(ctx, client, IdentitiesDirectory, "", func(entry *filer_pb.Entry, isLast bool) error { |
|||
if !entry.IsDirectory && strings.HasSuffix(entry.Name, ".json") { |
|||
existingFileNames[entry.Name] = true |
|||
} |
|||
return nil |
|||
}, "", false, 10000) |
|||
|
|||
if err != nil && err != filer_pb.ErrNotFound { |
|||
return fmt.Errorf("failed to list existing identities: %w", err) |
|||
} |
|||
|
|||
// 2. Build a set of identity keys present in the provided config
|
|||
newKeys := make(map[string]bool) |
|||
for _, identity := range config.Identities { |
|||
newKeys[identity.Name+".json"] = true |
|||
} |
|||
|
|||
// 3. Write/overwrite each identity using saveIdentity
|
|||
for _, identity := range config.Identities { |
|||
if err := store.saveIdentity(ctx, client, identity); err != nil { |
|||
return err |
|||
} |
|||
} |
|||
|
|||
// 4. Delete any existing files whose identity key is not in the new set
|
|||
for filename := range existingFileNames { |
|||
if !newKeys[filename] { |
|||
err := filer_pb.DoRemove(ctx, client, IdentitiesDirectory, filename, false, false, false, false, nil) |
|||
if err != nil && err != filer_pb.ErrNotFound { |
|||
glog.Warningf("failed to remove stale identity file %s: %v", filename, err) |
|||
} |
|||
} |
|||
} |
|||
|
|||
return nil |
|||
}) |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) saveIdentity(ctx context.Context, client filer_pb.SeaweedFilerClient, identity *iam_pb.Identity) error { |
|||
data, err := json.Marshal(identity) |
|||
if err != nil { |
|||
return fmt.Errorf("failed to marshal identity %s: %w", identity.Name, err) |
|||
} |
|||
|
|||
filename := identity.Name + ".json" |
|||
return filer.SaveInsideFiler(client, IdentitiesDirectory, filename, data) |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) CreateUser(ctx context.Context, identity *iam_pb.Identity) error { |
|||
return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
filename := identity.Name + ".json" |
|||
// Check if exists
|
|||
exists, err := store.exists(ctx, client, IdentitiesDirectory, filename) |
|||
if err != nil { |
|||
return err |
|||
} |
|||
if exists { |
|||
return credential.ErrUserAlreadyExists |
|||
} |
|||
|
|||
return store.saveIdentity(ctx, client, identity) |
|||
}) |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) exists(ctx context.Context, client filer_pb.SeaweedFilerClient, dir, name string) (bool, error) { |
|||
request := &filer_pb.LookupDirectoryEntryRequest{ |
|||
Directory: dir, |
|||
Name: name, |
|||
} |
|||
resp, err := filer_pb.LookupEntry(ctx, client, request) |
|||
if err != nil { |
|||
if err == filer_pb.ErrNotFound { |
|||
return false, nil |
|||
} |
|||
return false, err |
|||
} |
|||
return resp.Entry != nil, nil |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) GetUser(ctx context.Context, username string) (*iam_pb.Identity, error) { |
|||
var identity *iam_pb.Identity |
|||
err := store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
filename := username + ".json" |
|||
content, err := filer.ReadInsideFiler(client, IdentitiesDirectory, filename) |
|||
if err != nil { |
|||
if err == filer_pb.ErrNotFound { |
|||
return credential.ErrUserNotFound |
|||
} |
|||
return err |
|||
} |
|||
|
|||
identity = &iam_pb.Identity{} |
|||
if err := json.Unmarshal(content, identity); err != nil { |
|||
return fmt.Errorf("failed to parse identity: %w", err) |
|||
} |
|||
return nil |
|||
}) |
|||
return identity, err |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) UpdateUser(ctx context.Context, username string, identity *iam_pb.Identity) error { |
|||
return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
filename := username + ".json" |
|||
// Check if exists
|
|||
exists, err := store.exists(ctx, client, IdentitiesDirectory, filename) |
|||
if err != nil { |
|||
return err |
|||
} |
|||
if !exists { |
|||
return credential.ErrUserNotFound |
|||
} |
|||
|
|||
// If username changed (renamed), we need to create new file and then delete old one
|
|||
if identity.Name != username { |
|||
// Check if the new username already exists to prevent overwrites
|
|||
newFilename := identity.Name + ".json" |
|||
exists, err := store.exists(ctx, client, IdentitiesDirectory, newFilename) |
|||
if err != nil { |
|||
return err |
|||
} |
|||
if exists { |
|||
return fmt.Errorf("user %s already exists", identity.Name) |
|||
} |
|||
|
|||
// Create new identity file FIRST
|
|||
if err := store.saveIdentity(ctx, client, identity); err != nil { |
|||
return err |
|||
} |
|||
|
|||
// Delete old user file SECOND
|
|||
err = filer_pb.DoRemove(ctx, client, IdentitiesDirectory, filename, false, false, false, false, nil) |
|||
if err != nil && err != filer_pb.ErrNotFound { |
|||
// Rollback: try to remove the newly created file if deleting the old one failed
|
|||
if errRollback := filer_pb.DoRemove(ctx, client, IdentitiesDirectory, newFilename, false, false, false, false, nil); errRollback != nil { |
|||
glog.Errorf("Rollback of creating %s failed after failing to remove %s: %v", newFilename, filename, errRollback) |
|||
} |
|||
return fmt.Errorf("failed to remove old identity file %s: %w", filename, err) |
|||
} |
|||
return nil |
|||
} |
|||
|
|||
return store.saveIdentity(ctx, client, identity) |
|||
}) |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) DeleteUser(ctx context.Context, username string) error { |
|||
return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
filename := username + ".json" |
|||
err := filer_pb.DoRemove(ctx, client, IdentitiesDirectory, filename, false, false, false, false, nil) |
|||
if err != nil { |
|||
if err == filer_pb.ErrNotFound { |
|||
return nil |
|||
} |
|||
return err |
|||
} |
|||
return nil |
|||
}) |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) ListUsers(ctx context.Context) ([]string, error) { |
|||
var usernames []string |
|||
err := store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
err := filer_pb.SeaweedList(ctx, client, IdentitiesDirectory, "", func(entry *filer_pb.Entry, isLast bool) error { |
|||
if !entry.IsDirectory && strings.HasSuffix(entry.Name, ".json") { |
|||
name := strings.TrimSuffix(entry.Name, ".json") |
|||
usernames = append(usernames, name) |
|||
} |
|||
return nil |
|||
}, "", false, 10000) |
|||
|
|||
if err != nil { |
|||
if err == filer_pb.ErrNotFound { |
|||
// Treat as empty if directory not found
|
|||
return nil |
|||
} |
|||
return err |
|||
} |
|||
return nil |
|||
}) |
|||
return usernames, err |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) GetUserByAccessKey(ctx context.Context, accessKey string) (*iam_pb.Identity, error) { |
|||
// This is inefficient in file store without index.
|
|||
// We must iterate all users.
|
|||
config, err := store.LoadConfiguration(ctx) |
|||
if err != nil { |
|||
return nil, err |
|||
} |
|||
|
|||
for _, identity := range config.Identities { |
|||
for _, credential := range identity.Credentials { |
|||
if credential.AccessKey == accessKey { |
|||
return identity, nil |
|||
} |
|||
} |
|||
} |
|||
|
|||
return nil, credential.ErrAccessKeyNotFound |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) CreateAccessKey(ctx context.Context, username string, cred *iam_pb.Credential) error { |
|||
identity, err := store.GetUser(ctx, username) |
|||
if err != nil { |
|||
return err |
|||
} |
|||
|
|||
// Check duplicates
|
|||
for _, existing := range identity.Credentials { |
|||
if existing.AccessKey == cred.AccessKey { |
|||
return fmt.Errorf("access key already exists") |
|||
} |
|||
} |
|||
|
|||
identity.Credentials = append(identity.Credentials, cred) |
|||
return store.UpdateUser(ctx, username, identity) |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) DeleteAccessKey(ctx context.Context, username string, accessKey string) error { |
|||
identity, err := store.GetUser(ctx, username) |
|||
if err != nil { |
|||
return err |
|||
} |
|||
|
|||
found := false |
|||
for i, cred := range identity.Credentials { |
|||
if cred.AccessKey == accessKey { |
|||
identity.Credentials = append(identity.Credentials[:i], identity.Credentials[i+1:]...) |
|||
found = true |
|||
break |
|||
} |
|||
} |
|||
|
|||
if !found { |
|||
return credential.ErrAccessKeyNotFound |
|||
} |
|||
|
|||
return store.UpdateUser(ctx, username, identity) |
|||
} |
|||
|
|||
// PolicyManager implementation
|
|||
|
|||
func (store *FilerMultipleStore) GetPolicies(ctx context.Context) (map[string]policy_engine.PolicyDocument, error) { |
|||
policies := make(map[string]policy_engine.PolicyDocument) |
|||
|
|||
err := store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
return filer_pb.SeaweedList(ctx, client, PoliciesDirectory, "", func(entry *filer_pb.Entry, isLast bool) error { |
|||
if entry.IsDirectory || !strings.HasSuffix(entry.Name, ".json") { |
|||
return nil |
|||
} |
|||
|
|||
content, err := filer.ReadInsideFiler(client, PoliciesDirectory, entry.Name) |
|||
if err != nil { |
|||
glog.Warningf("Failed to read policy file %s: %v", entry.Name, err) |
|||
return nil |
|||
} |
|||
|
|||
var policy policy_engine.PolicyDocument |
|||
if err := json.Unmarshal(content, &policy); err != nil { |
|||
glog.Warningf("Failed to parse policy file %s: %v", entry.Name, err) |
|||
return nil |
|||
} |
|||
|
|||
name := strings.TrimSuffix(entry.Name, ".json") |
|||
policies[name] = policy |
|||
return nil |
|||
}, "", false, 10000) |
|||
}) |
|||
|
|||
if err != nil { |
|||
if err == filer_pb.ErrNotFound { |
|||
return policies, nil |
|||
} |
|||
return nil, err |
|||
} |
|||
|
|||
return policies, nil |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) CreatePolicy(ctx context.Context, name string, document policy_engine.PolicyDocument) error { |
|||
return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
filename := name + ".json" |
|||
exists, err := store.exists(ctx, client, PoliciesDirectory, filename) |
|||
if err != nil { |
|||
return err |
|||
} |
|||
if exists { |
|||
return fmt.Errorf("policy %s already exists", name) |
|||
} |
|||
|
|||
return store.savePolicy(ctx, client, name, document) |
|||
}) |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) PutPolicy(ctx context.Context, name string, document policy_engine.PolicyDocument) error { |
|||
return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
// We can just overwrite. The distinction between Create and Update in filer_multiple was just checking existence.
|
|||
// Put implies "create or replace".
|
|||
return store.savePolicy(ctx, client, name, document) |
|||
}) |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) UpdatePolicy(ctx context.Context, name string, document policy_engine.PolicyDocument) error { |
|||
return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
filename := name + ".json" |
|||
exists, err := store.exists(ctx, client, PoliciesDirectory, filename) |
|||
if err != nil { |
|||
return err |
|||
} |
|||
if !exists { |
|||
return fmt.Errorf("policy %s not found", name) |
|||
} |
|||
|
|||
return store.savePolicy(ctx, client, name, document) |
|||
}) |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) DeletePolicy(ctx context.Context, name string) error { |
|||
return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
filename := name + ".json" |
|||
err := filer_pb.DoRemove(ctx, client, PoliciesDirectory, filename, false, false, false, false, nil) |
|||
if err != nil { |
|||
if err == filer_pb.ErrNotFound { |
|||
return nil |
|||
} |
|||
return err |
|||
} |
|||
return nil |
|||
}) |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) GetPolicy(ctx context.Context, name string) (*policy_engine.PolicyDocument, error) { |
|||
var policy *policy_engine.PolicyDocument |
|||
err := store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { |
|||
filename := name + ".json" |
|||
content, err := filer.ReadInsideFiler(client, PoliciesDirectory, filename) |
|||
if err != nil { |
|||
if err == filer_pb.ErrNotFound { |
|||
return nil |
|||
} |
|||
return err |
|||
} |
|||
|
|||
policy = &policy_engine.PolicyDocument{} |
|||
if err := json.Unmarshal(content, policy); err != nil { |
|||
return fmt.Errorf("failed to parse policy: %w", err) |
|||
} |
|||
return nil |
|||
}) |
|||
return policy, err |
|||
} |
|||
|
|||
func (store *FilerMultipleStore) savePolicy(ctx context.Context, client filer_pb.SeaweedFilerClient, name string, document policy_engine.PolicyDocument) error { |
|||
data, err := json.Marshal(document) |
|||
if err != nil { |
|||
return fmt.Errorf("failed to marshal policy %s: %w", name, err) |
|||
} |
|||
|
|||
filename := name + ".json" |
|||
return filer.SaveInsideFiler(client, PoliciesDirectory, filename, data) |
|||
} |
|||
@ -0,0 +1,78 @@ |
|||
package grpc |
|||
|
|||
import ( |
|||
"context" |
|||
|
|||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" |
|||
) |
|||
|
|||
func (store *IamGrpcStore) CreateServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) error { |
|||
return store.withIamClient(func(client iam_pb.SeaweedIdentityAccessManagementClient) error { |
|||
_, err := client.CreateServiceAccount(ctx, &iam_pb.CreateServiceAccountRequest{ |
|||
ServiceAccount: sa, |
|||
}) |
|||
return err |
|||
}) |
|||
} |
|||
|
|||
func (store *IamGrpcStore) UpdateServiceAccount(ctx context.Context, id string, sa *iam_pb.ServiceAccount) error { |
|||
return store.withIamClient(func(client iam_pb.SeaweedIdentityAccessManagementClient) error { |
|||
_, err := client.UpdateServiceAccount(ctx, &iam_pb.UpdateServiceAccountRequest{ |
|||
Id: id, |
|||
ServiceAccount: sa, |
|||
}) |
|||
return err |
|||
}) |
|||
} |
|||
|
|||
func (store *IamGrpcStore) DeleteServiceAccount(ctx context.Context, id string) error { |
|||
return store.withIamClient(func(client iam_pb.SeaweedIdentityAccessManagementClient) error { |
|||
_, err := client.DeleteServiceAccount(ctx, &iam_pb.DeleteServiceAccountRequest{ |
|||
Id: id, |
|||
}) |
|||
return err |
|||
}) |
|||
} |
|||
|
|||
func (store *IamGrpcStore) GetServiceAccount(ctx context.Context, id string) (*iam_pb.ServiceAccount, error) { |
|||
var sa *iam_pb.ServiceAccount |
|||
err := store.withIamClient(func(client iam_pb.SeaweedIdentityAccessManagementClient) error { |
|||
resp, err := client.GetServiceAccount(ctx, &iam_pb.GetServiceAccountRequest{ |
|||
Id: id, |
|||
}) |
|||
if err != nil { |
|||
return err |
|||
} |
|||
sa = resp.ServiceAccount |
|||
return nil |
|||
}) |
|||
return sa, err |
|||
} |
|||
|
|||
func (store *IamGrpcStore) ListServiceAccounts(ctx context.Context) ([]*iam_pb.ServiceAccount, error) { |
|||
var accounts []*iam_pb.ServiceAccount |
|||
err := store.withIamClient(func(client iam_pb.SeaweedIdentityAccessManagementClient) error { |
|||
resp, err := client.ListServiceAccounts(ctx, &iam_pb.ListServiceAccountsRequest{}) |
|||
if err != nil { |
|||
return err |
|||
} |
|||
accounts = resp.ServiceAccounts |
|||
return nil |
|||
}) |
|||
return accounts, err |
|||
} |
|||
|
|||
func (store *IamGrpcStore) GetServiceAccountByAccessKey(ctx context.Context, accessKey string) (*iam_pb.ServiceAccount, error) { |
|||
var sa *iam_pb.ServiceAccount |
|||
err := store.withIamClient(func(client iam_pb.SeaweedIdentityAccessManagementClient) error { |
|||
resp, err := client.GetServiceAccountByAccessKey(ctx, &iam_pb.GetServiceAccountByAccessKeyRequest{ |
|||
AccessKey: accessKey, |
|||
}) |
|||
if err != nil { |
|||
return err |
|||
} |
|||
sa = resp.ServiceAccount |
|||
return nil |
|||
}) |
|||
return sa, err |
|||
} |
|||
@ -0,0 +1,85 @@ |
|||
package memory |
|||
|
|||
import ( |
|||
"context" |
|||
"fmt" |
|||
|
|||
"github.com/seaweedfs/seaweedfs/weed/credential" |
|||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" |
|||
) |
|||
|
|||
func (store *MemoryStore) CreateServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) error { |
|||
store.mu.Lock() |
|||
defer store.mu.Unlock() |
|||
|
|||
if _, exists := store.serviceAccounts[sa.Id]; exists { |
|||
return fmt.Errorf("service account already exists") |
|||
} |
|||
store.serviceAccounts[sa.Id] = sa |
|||
if sa.Credential != nil && sa.Credential.AccessKey != "" { |
|||
store.serviceAccountAccessKeys[sa.Credential.AccessKey] = sa.Id |
|||
} |
|||
return nil |
|||
} |
|||
|
|||
func (store *MemoryStore) UpdateServiceAccount(ctx context.Context, id string, sa *iam_pb.ServiceAccount) error { |
|||
store.mu.Lock() |
|||
defer store.mu.Unlock() |
|||
|
|||
_, exists := store.serviceAccounts[id] |
|||
if !exists { |
|||
return credential.ErrServiceAccountNotFound |
|||
} |
|||
if sa.Id != id { |
|||
return fmt.Errorf("service account ID mismatch") |
|||
} |
|||
|
|||
// Update access key index: remove any existing keys for this SA
|
|||
for k, v := range store.serviceAccountAccessKeys { |
|||
if v == id { |
|||
delete(store.serviceAccountAccessKeys, k) |
|||
} |
|||
} |
|||
|
|||
store.serviceAccounts[id] = sa |
|||
|
|||
if sa.Credential != nil && sa.Credential.AccessKey != "" { |
|||
store.serviceAccountAccessKeys[sa.Credential.AccessKey] = sa.Id |
|||
} |
|||
return nil |
|||
} |
|||
|
|||
func (store *MemoryStore) DeleteServiceAccount(ctx context.Context, id string) error { |
|||
store.mu.Lock() |
|||
defer store.mu.Unlock() |
|||
|
|||
if sa, ok := store.serviceAccounts[id]; ok { |
|||
if sa.Credential != nil && sa.Credential.AccessKey != "" { |
|||
delete(store.serviceAccountAccessKeys, sa.Credential.AccessKey) |
|||
} |
|||
delete(store.serviceAccounts, id) |
|||
return nil |
|||
} |
|||
return credential.ErrServiceAccountNotFound |
|||
} |
|||
|
|||
func (store *MemoryStore) GetServiceAccount(ctx context.Context, id string) (*iam_pb.ServiceAccount, error) { |
|||
store.mu.RLock() |
|||
defer store.mu.RUnlock() |
|||
|
|||
if sa, exists := store.serviceAccounts[id]; exists { |
|||
return sa, nil |
|||
} |
|||
return nil, credential.ErrServiceAccountNotFound |
|||
} |
|||
|
|||
func (store *MemoryStore) ListServiceAccounts(ctx context.Context) ([]*iam_pb.ServiceAccount, error) { |
|||
store.mu.RLock() |
|||
defer store.mu.RUnlock() |
|||
|
|||
var accounts []*iam_pb.ServiceAccount |
|||
for _, sa := range store.serviceAccounts { |
|||
accounts = append(accounts, sa) |
|||
} |
|||
return accounts, nil |
|||
} |
|||
@ -0,0 +1,173 @@ |
|||
package postgres |
|||
|
|||
import ( |
|||
"context" |
|||
"database/sql" |
|||
"encoding/json" |
|||
"fmt" |
|||
|
|||
"github.com/seaweedfs/seaweedfs/weed/credential" |
|||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" |
|||
) |
|||
|
|||
func (store *PostgresStore) CreateServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) error { |
|||
if sa == nil { |
|||
return fmt.Errorf("service account is nil") |
|||
} |
|||
if sa.Id == "" { |
|||
return fmt.Errorf("service account ID is required") |
|||
} |
|||
if !store.configured { |
|||
return fmt.Errorf("store not configured") |
|||
} |
|||
|
|||
data, err := json.Marshal(sa) |
|||
if err != nil { |
|||
return fmt.Errorf("failed to marshal service account: %w", err) |
|||
} |
|||
|
|||
accessKey := "" |
|||
if sa.Credential != nil { |
|||
accessKey = sa.Credential.AccessKey |
|||
} |
|||
|
|||
_, err = store.db.ExecContext(ctx, |
|||
"INSERT INTO service_accounts (id, access_key, content) VALUES ($1, $2, $3)", |
|||
sa.Id, accessKey, data) |
|||
if err != nil { |
|||
return fmt.Errorf("failed to insert service account: %w", err) |
|||
} |
|||
return nil |
|||
} |
|||
|
|||
func (store *PostgresStore) UpdateServiceAccount(ctx context.Context, id string, sa *iam_pb.ServiceAccount) error { |
|||
if sa == nil { |
|||
return fmt.Errorf("service account is nil") |
|||
} |
|||
if id == "" { |
|||
return fmt.Errorf("service account ID is required") |
|||
} |
|||
if sa.Id != id { |
|||
return fmt.Errorf("service account ID mismatch") |
|||
} |
|||
|
|||
data, err := json.Marshal(sa) |
|||
if err != nil { |
|||
return fmt.Errorf("failed to marshal service account: %w", err) |
|||
} |
|||
|
|||
accessKey := "" |
|||
if sa.Credential != nil { |
|||
accessKey = sa.Credential.AccessKey |
|||
} |
|||
|
|||
result, err := store.db.ExecContext(ctx, |
|||
"UPDATE service_accounts SET access_key = $2, content = $3, updated_at = CURRENT_TIMESTAMP WHERE id = $1", |
|||
id, accessKey, data) |
|||
if err != nil { |
|||
return fmt.Errorf("failed to update service account: %w", err) |
|||
} |
|||
|
|||
rows, err := result.RowsAffected() |
|||
if err != nil { |
|||
return err |
|||
} |
|||
if rows == 0 { |
|||
return credential.ErrServiceAccountNotFound |
|||
} |
|||
return nil |
|||
} |
|||
|
|||
func (store *PostgresStore) DeleteServiceAccount(ctx context.Context, id string) error { |
|||
if !store.configured { |
|||
return fmt.Errorf("store not configured") |
|||
} |
|||
|
|||
result, err := store.db.ExecContext(ctx, "DELETE FROM service_accounts WHERE id = $1", id) |
|||
if err != nil { |
|||
return fmt.Errorf("failed to delete service account: %w", err) |
|||
} |
|||
|
|||
rows, err := result.RowsAffected() |
|||
if err != nil { |
|||
return err |
|||
} |
|||
if rows == 0 { |
|||
return credential.ErrServiceAccountNotFound |
|||
} |
|||
return nil |
|||
} |
|||
|
|||
func (store *PostgresStore) GetServiceAccount(ctx context.Context, id string) (*iam_pb.ServiceAccount, error) { |
|||
if !store.configured { |
|||
return nil, fmt.Errorf("store not configured") |
|||
} |
|||
|
|||
var content []byte |
|||
err := store.db.QueryRowContext(ctx, "SELECT content FROM service_accounts WHERE id = $1", id).Scan(&content) |
|||
if err != nil { |
|||
if err == sql.ErrNoRows { |
|||
return nil, credential.ErrServiceAccountNotFound |
|||
} |
|||
return nil, fmt.Errorf("failed to get service account: %w", err) |
|||
} |
|||
|
|||
sa := &iam_pb.ServiceAccount{} |
|||
if err := json.Unmarshal(content, sa); err != nil { |
|||
return nil, fmt.Errorf("failed to unmarshal service account: %w", err) |
|||
} |
|||
return sa, nil |
|||
} |
|||
|
|||
func (store *PostgresStore) ListServiceAccounts(ctx context.Context) ([]*iam_pb.ServiceAccount, error) { |
|||
if !store.configured { |
|||
return nil, fmt.Errorf("store not configured") |
|||
} |
|||
|
|||
rows, err := store.db.QueryContext(ctx, "SELECT content FROM service_accounts") |
|||
if err != nil { |
|||
return nil, fmt.Errorf("failed to list service accounts: %w", err) |
|||
} |
|||
defer rows.Close() |
|||
|
|||
var accounts []*iam_pb.ServiceAccount |
|||
for rows.Next() { |
|||
var content []byte |
|||
if err := rows.Scan(&content); err != nil { |
|||
return nil, fmt.Errorf("failed to scan service account: %w", err) |
|||
} |
|||
sa := &iam_pb.ServiceAccount{} |
|||
if err := json.Unmarshal(content, sa); err != nil { |
|||
return nil, fmt.Errorf("failed to unmarshal service account: %w", err) |
|||
} |
|||
accounts = append(accounts, sa) |
|||
} |
|||
|
|||
if err := rows.Err(); err != nil { |
|||
return nil, fmt.Errorf("error iterating service accounts: %w", err) |
|||
} |
|||
|
|||
return accounts, nil |
|||
} |
|||
|
|||
func (store *PostgresStore) GetServiceAccountByAccessKey(ctx context.Context, accessKey string) (*iam_pb.ServiceAccount, error) { |
|||
if !store.configured { |
|||
return nil, fmt.Errorf("store not configured") |
|||
} |
|||
|
|||
var content []byte |
|||
err := store.db.QueryRowContext(ctx, "SELECT content FROM service_accounts WHERE access_key = $1", accessKey).Scan(&content) |
|||
if err != nil { |
|||
if err == sql.ErrNoRows { |
|||
return nil, credential.ErrAccessKeyNotFound |
|||
} |
|||
return nil, fmt.Errorf("failed to query service account by access key: %w", err) |
|||
} |
|||
|
|||
sa := &iam_pb.ServiceAccount{} |
|||
if err := json.Unmarshal(content, sa); err != nil { |
|||
return nil, fmt.Errorf("failed to unmarshal service account: %w", err) |
|||
} |
|||
|
|||
return sa, nil |
|||
} |
|||
@ -0,0 +1,28 @@ |
|||
package credential |
|||
|
|||
import ( |
|||
"fmt" |
|||
"regexp" |
|||
) |
|||
|
|||
var ( |
|||
PolicyNamePattern = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) |
|||
ServiceAccountIdPattern = regexp.MustCompile(`^sa:[A-Za-z0-9_-]+:[a-z0-9-]+$`) |
|||
) |
|||
|
|||
func ValidatePolicyName(name string) error { |
|||
if !PolicyNamePattern.MatchString(name) { |
|||
return fmt.Errorf("invalid policy name: %s", name) |
|||
} |
|||
return nil |
|||
} |
|||
|
|||
func ValidateServiceAccountId(id string) error { |
|||
if id == "" { |
|||
return fmt.Errorf("service account ID cannot be empty") |
|||
} |
|||
if !ServiceAccountIdPattern.MatchString(id) { |
|||
return fmt.Errorf("invalid service account ID: %s (expected format sa:<user>:<uuid>)", id) |
|||
} |
|||
return nil |
|||
} |
|||
Write
Preview
Loading…
Cancel
Save
Reference in new issue