SeaweedFS is a distributed storage system for object storage (S3), file systems, Iceberg table buckets, and Lance vector buckets, designed to handle billions of files with O(1) disk access and effortless horizontal scaling.
Go blob-storagecloud-drivedistributed-file-systemdistributed-storageerasure-codingfusehadoop-hdfshdfskuberneteslancelancedbobject-storageposixs3s3-storageseaweedfstiered-file-systemvector-search
admin: add visual iam policy editor (#10878)
Mathieu Arnold641fc8b03107
diff --git a/weed/admin/dash/file_browser_data.go b/weed/admin/dash/file_browser_data.goindex 225b8dd417..07b770f6ac 100644--- a/weed/admin/dash/file_browser_data.go+++ b/weed/admin/dash/file_browser_data.go@@ -53,8 +53,11 @@ type FileBrowserData struct {CurrentLastFileName string `json:"current_last_file_name"` // Cursor from current request (for page size changes)}-// GetFileBrowser retrieves file browser data for a given path with cursor-based pagination-func (s *AdminServer) GetFileBrowser(dir string, lastFileName string, pageSize int) (*FileBrowserData, error) {+// GetFileBrowser retrieves file browser data for a given path with cursor-based+// pagination. A non-empty prefix limits the listing to entries whose name starts+// with it, so callers that only want part of a large directory don't have to page+// through all of it.+func (s *AdminServer) GetFileBrowser(dir string, prefix string, lastFileName string, pageSize int) (*FileBrowserData, error) {if dir == "" {dir = "/"}@@ -76,7 +79,7 @@ func (s *AdminServer) GetFileBrowser(dir string, lastFileName string, pageSize i// Fetch entries starting from the cursor (lastFileName)stream, err := client.ListEntries(context.Background(), &filer_pb.ListEntriesRequest{Directory: dir,- Prefix: "",+ Prefix: prefix,Limit: uint32(fetchLimit),StartFromFileName: lastFileName,InclusiveStartFrom: false, // Don't include the cursor file itselfdiff --git a/weed/admin/dash/principal_suggestions.go b/weed/admin/dash/principal_suggestions.gonew file mode 100644index 0000000000..a3a2256820--- /dev/null+++ b/weed/admin/dash/principal_suggestions.go@@ -0,0 +1,57 @@+package dash++import (+ "context"++ weediam "github.com/seaweedfs/seaweedfs/weed/iam"+ "github.com/seaweedfs/seaweedfs/weed/iam/integration"++ "github.com/seaweedfs/seaweedfs/weed/glog"+)++// principalRoleArn builds the ARN SeaweedFS assigns a role by default (when+// its RoleDefinition.RoleArn isn't explicitly set) - see+// weed/iam/integration/iam_manager.go's CreateRole. ListRoles only returns+// role names, so this reconstructs the well-known default rather than+// fetching every role's stored definition just to populate a suggestion list.+func principalRoleArn(roleName string) string {+ return "arn:aws:iam::role/" + roleName+}++// GetPrincipalSuggestions returns candidate ARNs for the policy editor's+// Principal/NotPrincipal autocomplete: one per S3 user, plus one per IAM+// role. Service accounts are deliberately not listed separately - a service+// account is just an additional credential for its parent user, so its ARN+// is identical to the one already suggested for that user.+//+// Role listing is best-effort: if the filer or role store is unavailable,+// the error is logged and suggestions fall back to users only, since an+// incomplete autocomplete list is far less disruptive than blocking policy+// editing over a suggestions-only feature.+func (s *AdminServer) GetPrincipalSuggestions(ctx context.Context) ([]string, error) {+ var suggestions []string++ users, err := s.GetObjectStoreUsers(ctx)+ if err != nil {+ return nil, err+ }+ for _, u := range users {+ suggestions = append(suggestions, weediam.UserArn(u.Username))+ }++ roleStore, err := integration.NewFilerRoleStore(nil, func() string { return s.GetFilerAddress() })+ if err != nil {+ glog.Warningf("GetPrincipalSuggestions: failed to create role store: %v", err)+ return suggestions, nil+ }+ roleNames, err := roleStore.ListRoles(ctx, s.GetFilerAddress())+ if err != nil {+ glog.Warningf("GetPrincipalSuggestions: failed to list roles: %v", err)+ return suggestions, nil+ }+ for _, roleName := range roleNames {+ suggestions = append(suggestions, principalRoleArn(roleName))+ }++ return suggestions, nil+}diff --git a/weed/admin/dash/principal_suggestions_test.go b/weed/admin/dash/principal_suggestions_test.gonew file mode 100644index 0000000000..8c3927ed13--- /dev/null+++ b/weed/admin/dash/principal_suggestions_test.go@@ -0,0 +1,11 @@+package dash++import "testing"++func TestPrincipalRoleArn(t *testing.T) {+ got := principalRoleArn("S3ReadOnlyRole")+ want := "arn:aws:iam::role/S3ReadOnlyRole"+ if got != want {+ t.Fatalf("principalRoleArn() = %q, want %q", got, want)+ }+}diff --git a/weed/admin/handlers/admin_handlers.go b/weed/admin/handlers/admin_handlers.goindex 0976424074..767790764f 100644--- a/weed/admin/handlers/admin_handlers.go+++ b/weed/admin/handlers/admin_handlers.go@@ -224,6 +224,10 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) {policyApi.Handle("/{name}", wrapWrite(h.policyHandlers.DeletePolicy)).Methods(http.MethodDelete)policyApi.HandleFunc("/validate", h.policyHandlers.ValidatePolicy).Methods(http.MethodPost)+ // Registered at the API root, not under policyApi: policyApi's "/{name}"+ // GET route would shadow any single-segment GET route registered after it.+ api.HandleFunc("/principals", h.policyHandlers.GetPrincipalSuggestions).Methods(http.MethodGet)+s3TablesApi := api.PathPrefix("/s3tables").Subrouter()s3TablesApi.HandleFunc("/buckets", h.adminServer.ListS3TablesBucketsAPI).Methods(http.MethodGet)s3TablesApi.Handle("/buckets", wrapWrite(h.adminServer.CreateS3TablesBucket)).Methods(http.MethodPost)@@ -253,6 +257,7 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) {filesApi.HandleFunc("/view", h.fileBrowserHandlers.ViewFile).Methods(http.MethodGet)filesApi.HandleFunc("/properties", h.fileBrowserHandlers.GetFileProperties).Methods(http.MethodGet)filesApi.HandleFunc("/metadata", h.fileBrowserHandlers.ExportMetadata).Methods(http.MethodGet)+ filesApi.HandleFunc("/list-folders", h.fileBrowserHandlers.ListFolders).Methods(http.MethodGet)volumeApi := api.PathPrefix("/volumes").Subrouter()volumeApi.HandleFunc("/export", h.clusterHandlers.ExportClusterVolumes).Methods(http.MethodGet)diff --git a/weed/admin/handlers/admin_handlers_routes_test.go b/weed/admin/handlers/admin_handlers_routes_test.goindex 521a4d3180..9cbd355281 100644--- a/weed/admin/handlers/admin_handlers_routes_test.go+++ b/weed/admin/handlers/admin_handlers_routes_test.go@@ -62,6 +62,48 @@ func TestSetupRoutes_RegistersBucketLifecycleAPI_WithAuth(t *testing.T) {assertHasRoute(t, router, http.MethodDelete, "/api/s3/buckets/example/lifecycle")}+func TestSetupRoutes_RegistersPolicyAPI_NoAuth(t *testing.T) {+ router := mux.NewRouter()++ newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)++ assertHasRoute(t, router, http.MethodGet, "/api/object-store/policies")+ assertHasRoute(t, router, http.MethodPost, "/api/object-store/policies")+ assertHasRoute(t, router, http.MethodGet, "/api/object-store/policies/example")+ assertHasRoute(t, router, http.MethodPut, "/api/object-store/policies/example")+ assertHasRoute(t, router, http.MethodDelete, "/api/object-store/policies/example")+ assertHasRoute(t, router, http.MethodPost, "/api/object-store/policies/validate")+}++func TestSetupRoutes_RegistersPolicyAPI_WithAuth(t *testing.T) {+ router := mux.NewRouter()++ newRouteTestAdminHandlers().SetupRoutes(router, true, "admin", "password", "", "", true)++ assertHasRoute(t, router, http.MethodGet, "/api/object-store/policies")+ assertHasRoute(t, router, http.MethodPost, "/api/object-store/policies")+ assertHasRoute(t, router, http.MethodGet, "/api/object-store/policies/example")+ assertHasRoute(t, router, http.MethodPut, "/api/object-store/policies/example")+ assertHasRoute(t, router, http.MethodDelete, "/api/object-store/policies/example")+ assertHasRoute(t, router, http.MethodPost, "/api/object-store/policies/validate")+}++func TestSetupRoutes_RegistersPrincipalsAPI_NoAuth(t *testing.T) {+ router := mux.NewRouter()++ newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)++ assertHasRoute(t, router, http.MethodGet, "/api/principals")+}++func TestSetupRoutes_RegistersFilesListFoldersAPI_NoAuth(t *testing.T) {+ router := mux.NewRouter()++ newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)++ assertHasRoute(t, router, http.MethodGet, "/api/files/list-folders")+}+func TestSetupRoutes_RegistersPluginPages_NoAuth(t *testing.T) {router := mux.NewRouter()diff --git a/weed/admin/handlers/file_browser_handlers.go b/weed/admin/handlers/file_browser_handlers.goindex e68b5db6f1..eb15c0355b 100644--- a/weed/admin/handlers/file_browser_handlers.go+++ b/weed/admin/handlers/file_browser_handlers.go@@ -66,7 +66,7 @@ func (h *FileBrowserHandlers) ShowFileBrowser(w http.ResponseWriter, r *http.Req}// Get file browser data with cursor-based pagination- browserData, err := h.adminServer.GetFileBrowser(path, lastFileName, pageSize)+ browserData, err := h.adminServer.GetFileBrowser(path, "", lastFileName, pageSize)if err != nil {writeJSONError(w, http.StatusInternalServerError, "Failed to get file browser data: "+err.Error())return@@ -778,3 +778,63 @@ func min(a, b int64) int64 {}return b}++// maxListFoldersEntries caps how many subfolder names ListFolders will+// collect for a single request, so a directory with an unusually large+// number of children can't turn one autocomplete keystroke into an+// unbounded, slow full-directory walk.+const maxListFoldersEntries = 2000++// maxListFoldersScanned caps how many entries ListFolders will page through+// looking for those subfolders. The folder cap alone doesn't bound the work:+// a bucket holding nothing but flat object keys has no subfolders to count,+// so the walk runs to the end of the directory - a million keys is a million+// entries read, 200 per round trip, behind a single keystroke.+const maxListFoldersScanned = 10000++// ListFolders returns, as JSON, the names of the subdirectories directly+// under the given path. It exists to back progressive autocomplete (e.g. the+// policy editor's Resource ARN field building up "bucket/folder/subfolder"+// one path segment at a time) rather than to be a general directory listing+// API, so it's restricted to paths under /buckets. The optional prefix is the+// segment the caller is still typing, and narrows the listing to it.+func (h *FileBrowserHandlers) ListFolders(w http.ResponseWriter, r *http.Request) {+ dirPath := defaultQuery(r.URL.Query().Get("path"), "/buckets")+ // Clean before the scope check: CleanWindowsPath only rewrites backslashes,+ // so "/buckets/../etc" would otherwise satisfy the prefix test below.+ dirPath = path.Clean(util.CleanWindowsPath(dirPath))++ if dirPath != "/buckets" && !strings.HasPrefix(dirPath, "/buckets/") {+ writeJSONError(w, http.StatusBadRequest, "path must be under /buckets")+ return+ }++ prefix := r.URL.Query().Get("prefix")++ folders := []string{}+ lastFileName := ""+ scanned := 0+ for {+ browserData, err := h.adminServer.GetFileBrowser(dirPath, prefix, lastFileName, 200)+ if err != nil {+ writeJSONError(w, http.StatusInternalServerError, "Failed to list directory: "+err.Error())+ return+ }+ scanned += len(browserData.Entries)+ for _, entry := range browserData.Entries {+ if entry.IsDirectory {+ folders = append(folders, entry.Name)+ if len(folders) >= maxListFoldersEntries {+ break+ }+ }+ }+ if len(browserData.Entries) == 0 || !browserData.HasNextPage ||+ len(folders) >= maxListFoldersEntries || scanned >= maxListFoldersScanned {+ break+ }+ lastFileName = browserData.Entries[len(browserData.Entries)-1].Name+ }++ writeJSON(w, http.StatusOK, map[string]interface{}{"folders": folders})+}diff --git a/weed/admin/handlers/file_browser_handlers_test.go b/weed/admin/handlers/file_browser_handlers_test.goindex 3baf9b3747..65d05dad9b 100644--- a/weed/admin/handlers/file_browser_handlers_test.go+++ b/weed/admin/handlers/file_browser_handlers_test.go@@ -1,7 +1,11 @@package handlersimport (+ "net/http"+ "net/http/httptest""testing"++ "github.com/seaweedfs/seaweedfs/weed/admin/dash")func TestValidateAndCleanFilePath_AllowsControlChars(t *testing.T) {@@ -42,3 +46,20 @@ func TestValidateAndCleanFilePath_RejectsEmpty(t *testing.T) {}}+func TestListFolders_RejectsPathOutsideBuckets(t *testing.T) {+ h := &FileBrowserHandlers{adminServer: &dash.AdminServer{}}++ cases := []string{"/etc/seaweedfs", "/", "/notbuckets/foo", "/buckets-not-really/foo",+ "/buckets/../etc", "/buckets/..", "/buckets/foo/../../etc", `/buckets\..\etc`}+ for _, path := range cases {+ req := httptest.NewRequest(http.MethodGet, "/api/files/list-folders?path="+path, nil)+ w := httptest.NewRecorder()++ h.ListFolders(w, req)++ if w.Code != http.StatusBadRequest {+ t.Errorf("path %q: expected 400, got %d (body: %s)", path, w.Code, w.Body.String())+ }+ }+}+diff --git a/weed/admin/handlers/policy_handlers.go b/weed/admin/handlers/policy_handlers.goindex 81868213ff..d9a6d786ee 100644--- a/weed/admin/handlers/policy_handlers.go+++ b/weed/admin/handlers/policy_handlers.go@@ -51,6 +51,17 @@ func (h *PolicyHandlers) GetPolicies(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, map[string]interface{}{"policies": policies})}+// GetPrincipalSuggestions returns candidate ARNs (existing users and IAM+// roles) for the policy editor's Principal/NotPrincipal autocomplete.+func (h *PolicyHandlers) GetPrincipalSuggestions(w http.ResponseWriter, r *http.Request) {+ suggestions, err := h.adminServer.GetPrincipalSuggestions(r.Context())+ if err != nil {+ writeJSONError(w, http.StatusInternalServerError, "Failed to get principal suggestions: "+err.Error())+ return+ }+ writeJSON(w, http.StatusOK, map[string]interface{}{"principals": suggestions})+}+// CreatePolicy handles policy creationfunc (h *PolicyHandlers) CreatePolicy(w http.ResponseWriter, r *http.Request) {var req dash.CreatePolicyRequest@@ -221,8 +232,18 @@ func (h *PolicyHandlers) ValidatePolicy(w http.ResponseWriter, r *http.Request)return}- if len(statement.Resource.Strings()) == 0 {- writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("Statement %d: Resource is required", i+1))+ if len(statement.Resource.Strings()) == 0 && len(statement.NotResource.Strings()) == 0 {+ writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("Statement %d: Resource or NotResource is required", i+1))+ return+ }++ if statement.Resource != nil && statement.NotResource != nil {+ writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("Statement %d: cannot specify both Resource and NotResource", i+1))+ return+ }++ if statement.Principal != nil && statement.NotPrincipal != nil {+ writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("Statement %d: cannot specify both Principal and NotPrincipal", i+1))return}}diff --git a/weed/admin/handlers/policy_handlers_test.go b/weed/admin/handlers/policy_handlers_test.gonew file mode 100644index 0000000000..21484148ba--- /dev/null+++ b/weed/admin/handlers/policy_handlers_test.go@@ -0,0 +1,161 @@+package handlers++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/seaweedfs/seaweedfs/weed/admin/dash"+ "github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"+)++func newValidatePolicyRequest(t *testing.T, document map[string]interface{}) *http.Request {+ t.Helper()+ body, err := json.Marshal(map[string]interface{}{"document": document})+ if err != nil {+ t.Fatalf("failed to marshal request body: %v", err)+ }+ req := httptest.NewRequest(http.MethodPost, "/api/object-store/policies/validate", bytes.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ return req+}++func TestValidatePolicy(t *testing.T) {+ handlers := &PolicyHandlers{adminServer: &dash.AdminServer{}}++ tests := []struct {+ name string+ document map[string]interface{}+ wantStatus int+ }{+ {+ name: "valid document with Resource",+ document: map[string]interface{}{+ "Version": "2012-10-17",+ "Statement": []map[string]interface{}{+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*"},+ },+ },+ wantStatus: http.StatusOK,+ },+ {+ name: "valid document with NotResource only",+ document: map[string]interface{}{+ "Version": "2012-10-17",+ "Statement": []map[string]interface{}{+ {"Effect": "Allow", "Action": "s3:GetObject", "NotResource": "arn:aws:s3:::secret-bucket/*"},+ },+ },+ wantStatus: http.StatusOK,+ },+ {+ name: "missing version",+ document: map[string]interface{}{+ "Statement": []map[string]interface{}{+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*"},+ },+ },+ wantStatus: http.StatusBadRequest,+ },+ {+ name: "no statements",+ document: map[string]interface{}{+ "Version": "2012-10-17",+ "Statement": []map[string]interface{}{},+ },+ wantStatus: http.StatusBadRequest,+ },+ {+ name: "invalid effect",+ document: map[string]interface{}{+ "Version": "2012-10-17",+ "Statement": []map[string]interface{}{+ {"Effect": "Maybe", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*"},+ },+ },+ wantStatus: http.StatusBadRequest,+ },+ {+ name: "missing action",+ document: map[string]interface{}{+ "Version": "2012-10-17",+ "Statement": []map[string]interface{}{+ {"Effect": "Allow", "Resource": "arn:aws:s3:::my-bucket/*"},+ },+ },+ wantStatus: http.StatusBadRequest,+ },+ {+ name: "neither Resource nor NotResource",+ document: map[string]interface{}{+ "Version": "2012-10-17",+ "Statement": []map[string]interface{}{+ {"Effect": "Allow", "Action": "s3:GetObject"},+ },+ },+ wantStatus: http.StatusBadRequest,+ },+ {+ name: "both Resource and NotResource",+ document: map[string]interface{}{+ "Version": "2012-10-17",+ "Statement": []map[string]interface{}{+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*", "NotResource": "arn:aws:s3:::secret-bucket/*"},+ },+ },+ wantStatus: http.StatusBadRequest,+ },+ {+ name: "empty Resource alongside non-empty NotResource is still a conflict",+ document: map[string]interface{}{+ "Version": "2012-10-17",+ "Statement": []map[string]interface{}{+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": []string{}, "NotResource": "arn:aws:s3:::secret-bucket/*"},+ },+ },+ wantStatus: http.StatusBadRequest,+ },+ {+ name: "both Principal and NotPrincipal",+ document: map[string]interface{}{+ "Version": "2012-10-17",+ "Statement": []map[string]interface{}{+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*", "Principal": "*", "NotPrincipal": "arn:aws:iam::123456789012:user/bob"},+ },+ },+ wantStatus: http.StatusBadRequest,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ req := newValidatePolicyRequest(t, tt.document)+ w := httptest.NewRecorder()++ handlers.ValidatePolicy(w, req)++ if w.Code != tt.wantStatus {+ t.Fatalf("expected status %d, got %d (body: %s)", tt.wantStatus, w.Code, w.Body.String())+ }+ })+ }+}++// Sanity check that policy_engine.PolicyStatement (the type ValidatePolicy+// actually decodes into) round-trips NotResource-only statements the way the+// test above assumes.+func TestValidatePolicy_NotResourceOnlyDecodes(t *testing.T) {+ raw := []byte(`{"Effect":"Allow","Action":"s3:GetObject","NotResource":"arn:aws:s3:::secret/*"}`)+ var stmt policy_engine.PolicyStatement+ if err := json.Unmarshal(raw, &stmt); err != nil {+ t.Fatalf("failed to unmarshal statement: %v", err)+ }+ if len(stmt.Resource.Strings()) != 0 {+ t.Fatalf("expected no Resource, got %v", stmt.Resource.Strings())+ }+ if len(stmt.NotResource.Strings()) != 1 {+ t.Fatalf("expected exactly one NotResource entry, got %v", stmt.NotResource.Strings())+ }+}diff --git a/weed/admin/view/app/policies.templ b/weed/admin/view/app/policies.templindex 6d7ade5dab..ac529054f5 100644--- a/weed/admin/view/app/policies.templ+++ b/weed/admin/view/app/policies.templ@@ -172,9 +172,52 @@ templ Policies(data dash.PoliciesData) {</div></div>+ <style>+ /* Groups a statement's Sid/Effect and its Action/Resource/Principal+ sections in the structured policy editor. Plain <fieldset>/<legend>+ render fine natively, but Bootstrap's form reset stretches <legend> to+ the fieldset's full width (float: left; width: 100%), which loses the+ usual "notch in the border" look and makes the label bar as wide as+ the card. Undo just that here so the legend hugs its content instead.+ */+ .policy-stmt-fieldset {+ border: 1px solid var(--bs-border-color, #dee2e6);+ border-radius: 0.375rem;+ padding: 0 0.75rem 0.75rem;+ margin: 0.75rem 0 0;+ }+ .policy-stmt-legend {+ float: none;+ width: auto;+ max-width: 100%;+ padding: 0 0.5rem;+ margin: 0 0 0.25rem;+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--bs-secondary-color, #6c757d);+ }+ </style>++ <!-- Datalist of suggested action names, shared by the create/edit editors -->+ <datalist id="policyActionSuggestions">+ for _, action := range PolicyActionSuggestions {+ <option value={action}></option>+ }+ </datalist>++ <!-- Populated dynamically as the user types in a Resource field: bucket+ names first, then subfolders one path segment at a time. See+ updatePolicyResourceSuggestions() below. -->+ <datalist id="policyResourceSuggestions"></datalist>++ <!-- Populated dynamically as the user types/focuses a Principal field:+ existing users and IAM roles, fetched once from /api/principals. See+ updatePolicyPrincipalSuggestions() below. -->+ <datalist id="policyPrincipalSuggestions"></datalist>+<!-- Create Policy Modal --><div class="modal fade" id="createPolicyModal" tabindex="-1" aria-labelledby="createPolicyModalLabel" aria-hidden="true">- <div class="modal-dialog modal-lg">+ <div class="modal-dialog modal-xl"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="createPolicyModalLabel">@@ -189,27 +232,36 @@ templ Policies(data dash.PoliciesData) {<input type="text" class="form-control" id="policyName" name="name" required placeholder="e.g., S3ReadOnlyPolicy"><div class="form-text">Enter a unique name for this policy (alphanumeric and underscores only)</div></div>-- <div class="mb-3">- <label for="policyDocument" class="form-label">Policy Document</label>- <textarea class="form-control" id="policyDocument" name="document" rows="15" required placeholder="Enter IAM policy JSON document..."></textarea>- <div class="form-text">Enter the policy document in AWS IAM JSON format</div>- </div>- <div class="mb-3">- <div class="row">- <div class="col-md-6">- <button type="button" class="btn btn-outline-info btn-sm" onclick="insertSamplePolicy()">- <i class="fas fa-file-alt me-1"></i>Use Sample Policy- </button>- </div>- <div class="col-md-6 text-end">- <button type="button" class="btn btn-outline-secondary btn-sm" onclick="validatePolicyDocument()">- <i class="fas fa-check me-1"></i>Validate JSON- </button>- </div>+ <ul class="nav nav-tabs" role="tablist">+ <li class="nav-item" role="presentation">+ <button class="nav-link active" id="createPolicyEditorTabBtn" type="button" data-bs-toggle="tab" data-bs-target="#createPolicyEditorTab">Editor</button>+ </li>+ <li class="nav-item" role="presentation">+ <button class="nav-link" id="createPolicyJsonTabBtn" type="button" data-bs-toggle="tab" data-bs-target="#createPolicyJsonTab">JSON</button>+ </li>+ </ul>+ <div class="tab-content border border-top-0 rounded-bottom p-3 mb-3">+ <div class="tab-pane fade show active" id="createPolicyEditorTab">+ <div id="createPolicyEditorBody"></div>+ <button type="button" class="btn btn-sm btn-outline-secondary" id="createPolicyAddStatementBtn">+ <i class="fas fa-plus me-1"></i>Add statement+ </button>+ </div>+ <div class="tab-pane fade" id="createPolicyJsonTab">+ <textarea class="form-control" id="policyDocument" name="document" rows="15" placeholder="Enter IAM policy JSON document..."></textarea>+ <div class="form-text">Enter the policy document in AWS IAM JSON format</div></div></div>++ <div class="mb-3 d-flex justify-content-between">+ <button type="button" class="btn btn-outline-info btn-sm" onclick="insertSamplePolicy('create')">+ <i class="fas fa-file-alt me-1"></i>Use Sample Policy+ </button>+ <button type="button" class="btn btn-outline-secondary btn-sm" onclick="validatePolicyDocument('create')">+ <i class="fas fa-check me-1"></i>Validate+ </button>+ </div></form></div><div class="modal-footer">@@ -254,7 +306,7 @@ templ Policies(data dash.PoliciesData) {<!-- Edit Policy Modal --><div class="modal fade" id="editPolicyModal" tabindex="-1" aria-labelledby="editPolicyModalLabel" aria-hidden="true">- <div class="modal-dialog modal-lg">+ <div class="modal-dialog modal-xl"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="editPolicyModalLabel">@@ -269,27 +321,36 @@ templ Policies(data dash.PoliciesData) {<input type="text" class="form-control" id="editPolicyName" name="name" readonly><div class="form-text">Policy name cannot be changed</div></div>-- <div class="mb-3">- <label for="editPolicyDocument" class="form-label">Policy Document</label>- <textarea class="form-control" id="editPolicyDocument" name="document" rows="15" required></textarea>- <div class="form-text">Edit the policy document in AWS IAM JSON format</div>- </div>- <div class="mb-3">- <div class="row">- <div class="col-md-6">- <button type="button" class="btn btn-outline-info btn-sm" onclick="insertSamplePolicyEdit()">- <i class="fas fa-file-alt me-1"></i>Reset to Sample- </button>- </div>- <div class="col-md-6 text-end">- <button type="button" class="btn btn-outline-secondary btn-sm" onclick="validateEditPolicyDocument()">- <i class="fas fa-check me-1"></i>Validate JSON- </button>- </div>+ <ul class="nav nav-tabs" role="tablist">+ <li class="nav-item" role="presentation">+ <button class="nav-link active" id="editPolicyEditorTabBtn" type="button" data-bs-toggle="tab" data-bs-target="#editPolicyEditorTab">Editor</button>+ </li>+ <li class="nav-item" role="presentation">+ <button class="nav-link" id="editPolicyJsonTabBtn" type="button" data-bs-toggle="tab" data-bs-target="#editPolicyJsonTab">JSON</button>+ </li>+ </ul>+ <div class="tab-content border border-top-0 rounded-bottom p-3 mb-3">+ <div class="tab-pane fade show active" id="editPolicyEditorTab">+ <div id="editPolicyEditorBody"></div>+ <button type="button" class="btn btn-sm btn-outline-secondary" id="editPolicyAddStatementBtn">+ <i class="fas fa-plus me-1"></i>Add statement+ </button>+ </div>+ <div class="tab-pane fade" id="editPolicyJsonTab">+ <textarea class="form-control" id="editPolicyDocument" name="document" rows="15"></textarea>+ <div class="form-text">Edit the policy document in AWS IAM JSON format</div></div></div>++ <div class="mb-3 d-flex justify-content-between">+ <button type="button" class="btn btn-outline-info btn-sm" onclick="insertSamplePolicy('edit')">+ <i class="fas fa-file-alt me-1"></i>Reset to Sample+ </button>+ <button type="button" class="btn btn-outline-secondary btn-sm" onclick="validatePolicyDocument('edit')">+ <i class="fas fa-check me-1"></i>Validate+ </button>+ </div></form></div><div class="modal-footer">@@ -306,9 +367,733 @@ templ Policies(data dash.PoliciesData) {<script>// Current policy being viewed/editedlet currentPolicy = null;-++ // Structured-editor state, one entry per modal ("create" / "edit"). Each+ // entry is { version, statements: [{ sid, effect, actions, resources, extras }] }.+ // "extras" holds the JSON text of any statement fields the structured+ // editor doesn't expose (Principal, NotPrincipal, NotResource, Condition,+ // or any future/unknown key), so they round-trip untouched.+ let policyEditors = {+ create: { version: '2012-10-17', statements: [], otherFields: {} },+ edit: { version: '2012-10-17', statements: [], otherFields: {} }+ };++ const POLICY_STATEMENT_KNOWN_KEYS = ['Sid', 'Effect', 'Action', 'Resource', 'NotResource'];++ // Shown for a policy that parsed as JSON but that the structured editor+ // can't represent, so its editor state carries { unparsed: true } and the+ // document only ever lives in the JSON tab.+ const POLICY_JSON_TAB_ONLY_MESSAGE = 'This policy can only be edited on the JSON tab.';++ // Maps a policy-list-item's data-field attribute to the editor-state+ // array it belongs to.+ const POLICY_LIST_FIELD_TO_STATE_KEY = { action: 'actions', resource: 'resources', principal: 'principalValues' };++ function policyTextareaId(which) {+ return which === 'create' ? 'policyDocument' : 'editPolicyDocument';+ }++ function policyEditorBodyId(which) {+ return which + 'PolicyEditorBody';+ }++ function normalizeToStringArray(value) {+ if (value === undefined || value === null) return [];+ // Coerce: these feed escapeHtml, which calls text.replace, and a+ // policy is free to carry a number or a boolean here.+ if (Array.isArray(value)) return value.map(String);+ return [String(value)];+ }++ const POLICY_DOCUMENT_KNOWN_KEYS = ['Version', 'Statement'];++ // Converts a policy document (as parsed from JSON) into editor state.+ //+ // Top-level keys the editor doesn't model (e.g. Id) are kept verbatim in+ // state.otherFields and merged back on serialization, so a round-trip+ // through the Editor tab doesn't rewrite text the user typed in the JSON+ // tab. The admin API's PolicyDocument only carries Version and Statement,+ // so such fields are still dropped by the server on save; see+ // confirmPolicyFieldDiscard, which warns the user before that happens.+ function policyDocToEditorState(doc) {+ if (doc === null || typeof doc !== 'object') {+ // null or a bare scalar (string/number/boolean) can't represent a+ // policy document; treating it as "zero statements" would hide+ // from the user that their input wasn't actually a document.+ throw new Error('Policy document must be a JSON object (got ' + JSON.stringify(doc) + ')');+ }+ const state = { version: doc.Version || '2012-10-17', statements: [], otherFields: {} };+ if (!Array.isArray(doc)) {+ Object.keys(doc).forEach(function(key) {+ if (POLICY_DOCUMENT_KNOWN_KEYS.indexOf(key) === -1) {+ state.otherFields[key] = doc[key];+ }+ });+ }+ const rawStatements = doc && doc.Statement+ ? (Array.isArray(doc.Statement) ? doc.Statement : [doc.Statement])+ : [];+ rawStatements.forEach(function(stmt, idx) {+ stmt = stmt || {};+ if (stmt.Effect !== 'Allow' && stmt.Effect !== 'Deny') {+ // Defaulting a missing/malformed Effect to "Allow" would+ // silently turn e.g. a typo'd "deny" into a permissive+ // statement. Reject instead of guessing.+ throw new Error('Statement ' + (idx + 1) + ': Effect must be exactly "Allow" or "Deny" (got ' ++ JSON.stringify(stmt.Effect === undefined ? null : stmt.Effect) + ')');+ }+ const hasResource = Object.prototype.hasOwnProperty.call(stmt, 'Resource');+ const hasNotResource = Object.prototype.hasOwnProperty.call(stmt, 'NotResource');+ if (hasResource && hasNotResource) {+ // The two are mutually exclusive; a document with both isn't+ // representable by the mode dropdown, so ask the user to fix+ // it in the JSON tab rather than silently picking one.+ throw new Error('Statement ' + (idx + 1) + ': cannot specify both Resource and NotResource');+ }+ const resourceMode = hasNotResource ? 'NotResource' : 'Resource';++ const hasPrincipal = Object.prototype.hasOwnProperty.call(stmt, 'Principal');+ const hasNotPrincipal = Object.prototype.hasOwnProperty.call(stmt, 'NotPrincipal');+ if (hasPrincipal && hasNotPrincipal) {+ throw new Error('Statement ' + (idx + 1) + ': cannot specify both Principal and NotPrincipal');+ }+ let principalMode = 'Principal';+ let principalValues = [];+ let principalManaged = false;+ let hasComplexPrincipal = false;+ if (hasPrincipal || hasNotPrincipal) {+ const principalKey = hasNotPrincipal ? 'NotPrincipal' : 'Principal';+ const parsedValues = parseSimpleAwsPrincipal(stmt[principalKey]);+ if (parsedValues) {+ principalMode = principalKey;+ principalValues = parsedValues;+ principalManaged = true;+ } else {+ // Bare string/array, a type other than AWS, or multiple+ // types at once - this v1 editor only models a single+ // {"AWS": ...} form. Leave it in extras rather than+ // guessing or discarding it.+ hasComplexPrincipal = true;+ }+ }++ const extras = {};+ Object.keys(stmt).forEach(function(key) {+ if (POLICY_STATEMENT_KNOWN_KEYS.indexOf(key) !== -1) return;+ if (principalManaged && (key === 'Principal' || key === 'NotPrincipal')) return;+ extras[key] = stmt[key];+ });+ state.statements.push({+ sid: String(stmt.Sid || ''),+ effect: stmt.Effect,+ actions: normalizeToStringArray(stmt.Action),+ resourceMode: resourceMode,+ resources: normalizeToStringArray(hasNotResource ? stmt.NotResource : stmt.Resource),+ principalMode: principalMode,+ principalValues: principalValues,+ hasComplexPrincipal: hasComplexPrincipal,+ extras: Object.keys(extras).length ? JSON.stringify(extras, null, 2) : ''+ });+ });+ return state;+ }++ // Returns the flattened list of values if `value` is a policy Principal /+ // NotPrincipal expressed as one of the two forms this editor's simple+ // text field models: the bare wildcard "*" (standard AWS shorthand for+ // "everyone"), or a single-key {"AWS": "..."} / {"AWS": ["...", ...]}+ // object. Returns null for anything else (any other bare string/array, a+ // different type key, or multiple type keys at once), which the caller+ // then leaves untouched in "extras".+ function parseSimpleAwsPrincipal(value) {+ if (value === '*') return ['*'];+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const keys = Object.keys(value);+ if (keys.length !== 1 || keys[0] !== 'AWS') return null;+ return normalizeToStringArray(value.AWS);+ }++ // Converts editor state back into a policy document. Structured fields+ // (Sid/Effect/Action/Resource-or-NotResource) always take precedence over+ // whatever is in "extras" in case of a conflicting key.+ //+ // Throws if a statement's "advanced fields" box holds malformed or+ // non-object JSON, instead of silently dropping it: those fields can+ // carry Principal/NotPrincipal/Condition, so silently continuing with an+ // empty object would change the policy's authorization behavior without+ // the user noticing.+ function policyEditorStateToDoc(state) {+ // Unmanaged top-level keys first, so Version/Statement below always win.+ const doc = Object.assign({}, state.otherFields || {});+ doc.Version = state.version || '2012-10-17';+ doc.Statement = [];+ (state.statements || []).forEach(function(s, idx) {+ let stmt = {};+ if (s.extras && s.extras.trim()) {+ let parsed;+ try {+ parsed = JSON.parse(s.extras);+ } catch (e) {+ throw new Error('Statement ' + (idx + 1) + ': advanced fields contain invalid JSON (' + e.message + ')');+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new Error('Statement ' + (idx + 1) + ': advanced fields must be a JSON object');+ }+ stmt = parsed;+ }+ if (s.sid) {+ stmt.Sid = s.sid;+ } else {+ delete stmt.Sid;+ }+ stmt.Effect = s.effect === 'Deny' ? 'Deny' : 'Allow';+ const actions = (s.actions || []).map(function(a) { return (a || '').trim(); }).filter(Boolean);+ if (actions.length) {+ stmt.Action = actions.length === 1 ? actions[0] : actions;+ } else {+ delete stmt.Action;+ }+ const resources = (s.resources || []).map(function(r) { return (r || '').trim(); }).filter(Boolean);+ if (resources.length) {+ // Resource and NotResource are mutually exclusive; only the+ // key matching the selected mode is ever written.+ if (s.resourceMode === 'NotResource') {+ stmt.NotResource = resources.length === 1 ? resources[0] : resources;+ delete stmt.Resource;+ } else {+ stmt.Resource = resources.length === 1 ? resources[0] : resources;+ delete stmt.NotResource;+ }+ } else {+ delete stmt.Resource;+ delete stmt.NotResource;+ }+ const principalValues = (s.principalValues || []).map(function(p) { return (p || '').trim(); }).filter(Boolean);+ if (principalValues.length) {+ // Same exclusivity rule as Resource/NotResource. Structured+ // values always win over whatever "extras" held for these+ // keys. A lone "*" is written as the bare wildcard (standard+ // AWS shorthand for "everyone"); anything else is wrapped in+ // the standard {"AWS": ...} form (v1 only models AWS+ // principals).+ delete stmt.Principal;+ delete stmt.NotPrincipal;+ const wrappedPrincipal = (principalValues.length === 1 && principalValues[0] === '*')+ ? '*'+ : { AWS: principalValues.length === 1 ? principalValues[0] : principalValues };+ if (s.principalMode === 'NotPrincipal') {+ stmt.NotPrincipal = wrappedPrincipal;+ } else {+ stmt.Principal = wrappedPrincipal;+ }+ }+ // If principalValues is empty, leave stmt.Principal/NotPrincipal+ // untouched: it may hold a complex form preserved verbatim from+ // "extras" (see parseSimpleAwsPrincipal) that the user never+ // touched via this field, and clearing it here would silently+ // discard it.+ doc.Statement.push(stmt);+ });+ return doc;+ }++ // Renders the structured editor for the given modal ("create"/"edit")+ // from policyEditors[which] into its container.+ function renderPolicyEditor(which) {+ const container = document.getElementById(policyEditorBodyId(which));+ if (!container) return;+ const state = policyEditors[which];++ if (state.unparsed) {+ container.innerHTML = '<p class="text-muted">This policy uses a form the structured editor cannot show. Edit it on the JSON tab.</p>';+ return;+ }++ if (state.statements.length === 0) {+ container.innerHTML = '<p class="text-muted">No statements yet. Click "Add statement" to create one.</p>';+ return;+ }++ let html = '';+ state.statements.forEach(function(stmt, idx) {+ const actionRows = stmt.actions.map(function(action, actionIdx) {+ return policyListRowHtml(which, idx, 'action', actionIdx, action);+ }).join('');+ const resourceRows = stmt.resources.map(function(resource, resourceIdx) {+ return policyListRowHtml(which, idx, 'resource', resourceIdx, resource);+ }).join('');+ const principalRows = stmt.principalValues.map(function(principal, principalIdx) {+ return policyListRowHtml(which, idx, 'principal', principalIdx, principal);+ }).join('');++ html +=+ '<div class="card mb-3" data-statement-index="' + idx + '">' ++ '<div class="card-body">' ++ '<div class="d-flex justify-content-between align-items-start mb-2">' ++ '<h6 class="card-title mb-0">Statement ' + (idx + 1) + '</h6>' ++ '<button type="button" class="btn btn-sm btn-outline-danger policy-remove-statement-btn" data-which="' + which + '" data-index="' + idx + '"><i class="fas fa-trash"></i></button>' ++ '</div>' ++ '<div class="row mb-2">' ++ '<div class="col-md-6">' ++ '<label class="form-label">Sid (optional)</label>' ++ '<input type="text" class="form-control form-control-sm policy-stmt-sid" data-which="' + which + '" data-index="' + idx + '" value="' + escapeHtml(stmt.sid) + '">' ++ '</div>' ++ '<div class="col-md-6">' ++ '<label class="form-label d-block">Effect</label>' ++ '<div class="btn-group" role="group">' ++ '<input type="radio" class="btn-check policy-stmt-effect" name="policyEffect-' + which + '-' + idx + '" id="policyEffectAllow-' + which + '-' + idx + '" data-which="' + which + '" data-index="' + idx + '" value="Allow"' + (stmt.effect === 'Allow' ? ' checked' : '') + '>' ++ '<label class="btn btn-outline-success btn-sm" for="policyEffectAllow-' + which + '-' + idx + '">Allow</label>' ++ '<input type="radio" class="btn-check policy-stmt-effect" name="policyEffect-' + which + '-' + idx + '" id="policyEffectDeny-' + which + '-' + idx + '" data-which="' + which + '" data-index="' + idx + '" value="Deny"' + (stmt.effect === 'Deny' ? ' checked' : '') + '>' ++ '<label class="btn btn-outline-danger btn-sm" for="policyEffectDeny-' + which + '-' + idx + '">Deny</label>' ++ '</div>' ++ '</div>' ++ '</div>' ++ '<fieldset class="policy-stmt-fieldset">' ++ '<legend class="policy-stmt-legend border rounded">Actions</legend>' ++ '<div class="policy-action-rows" data-which="' + which + '" data-index="' + idx + '">' + actionRows + '</div>' ++ '<button type="button" class="btn btn-sm btn-outline-secondary policy-add-list-item-btn" data-which="' + which + '" data-index="' + idx + '" data-field="action"><i class="fas fa-plus me-1"></i>Add action</button>' ++ '</fieldset>' ++ '<fieldset class="policy-stmt-fieldset">' ++ '<legend class="policy-stmt-legend">' ++ '<select class="form-select form-select-sm d-inline-block w-auto policy-stmt-resource-mode" data-which="' + which + '" data-index="' + idx + '">' ++ '<option value="Resource"' + (stmt.resourceMode !== 'NotResource' ? ' selected' : '') + '>Resource</option>' ++ '<option value="NotResource"' + (stmt.resourceMode === 'NotResource' ? ' selected' : '') + '>NotResource</option>' ++ '</select>' ++ '</legend>' ++ (stmt.resourceMode === 'NotResource' ? '<div class="form-text mt-0 mb-1">The statement applies to every resource except the ones listed.</div>' : '') ++ '<div class="policy-resource-rows" data-which="' + which + '" data-index="' + idx + '">' + resourceRows + '</div>' ++ '<button type="button" class="btn btn-sm btn-outline-secondary policy-add-list-item-btn" data-which="' + which + '" data-index="' + idx + '" data-field="resource"><i class="fas fa-plus me-1"></i>Add resource</button>' ++ '</fieldset>' ++ '<fieldset class="policy-stmt-fieldset">' ++ '<legend class="policy-stmt-legend">' ++ '<select class="form-select form-select-sm d-inline-block w-auto policy-stmt-principal-mode" data-which="' + which + '" data-index="' + idx + '">' ++ '<option value="Principal"' + (stmt.principalMode !== 'NotPrincipal' ? ' selected' : '') + '>Principal</option>' ++ '<option value="NotPrincipal"' + (stmt.principalMode === 'NotPrincipal' ? ' selected' : '') + '>NotPrincipal</option>' ++ '</select>' ++ '</legend>' ++ '<div class="form-text mt-0 mb-1">Principal / NotPrincipal (AWS account/user ARN, or "*" for everyone). Only the AWS type and "*" are supported here; other forms stay editable via Advanced fields.</div>' ++ (stmt.hasComplexPrincipal ? '<div class="form-text text-warning mt-0 mb-1"><i class="fas fa-triangle-exclamation me-1"></i>This statement\'s Principal/NotPrincipal uses a form not supported by this field — see Advanced fields below.</div>' : '') ++ '<div class="policy-principal-rows" data-which="' + which + '" data-index="' + idx + '">' + principalRows + '</div>' ++ '<button type="button" class="btn btn-sm btn-outline-secondary policy-add-list-item-btn" data-which="' + which + '" data-index="' + idx + '" data-field="principal"><i class="fas fa-plus me-1"></i>Add principal</button>' ++ '</fieldset>' ++ '<details class="mt-3"' + (stmt.extras ? ' open' : '') + '>' ++ '<summary class="text-muted">Advanced fields (Principal, NotPrincipal, Condition, raw JSON)</summary>' ++ '<textarea class="form-control form-control-sm mt-2 policy-stmt-extras" data-which="' + which + '" data-index="' + idx + '" rows="4" placeholder="{}">' + escapeHtml(stmt.extras) + '</textarea>' ++ '</details>' ++ '</div>' ++ '</div>';+ });+ container.innerHTML = html;+ }++ function policyListRowHtml(which, stmtIdx, field, itemIdx, value) {+ let listAttr = '';+ if (field === 'action') listAttr = ' list="policyActionSuggestions"';+ else if (field === 'resource') listAttr = ' list="policyResourceSuggestions"';+ else if (field === 'principal') listAttr = ' list="policyPrincipalSuggestions"';+ return '<div class="input-group input-group-sm mb-1">' ++ '<input type="text" class="form-control policy-list-item" ' + listAttr + ' data-which="' + which + '" data-index="' + stmtIdx + '" data-field="' + field + '" data-item-index="' + itemIdx + '" value="' + escapeHtml(value) + '">' ++ '<button type="button" class="btn btn-outline-danger policy-remove-list-item-btn" data-which="' + which + '" data-index="' + stmtIdx + '" data-field="' + field + '" data-item-index="' + itemIdx + '"><i class="fas fa-times"></i></button>' ++ '</div>';+ }++ // Reads whatever is currently displayed in the editor tab's DOM back into+ // policyEditors[which], so nothing typed is lost before a save/tab-switch/serialize.+ function commitPolicyEditorForm(which) {+ const state = policyEditors[which];+ if (!state) return;++ document.querySelectorAll('.policy-stmt-sid[data-which="' + which + '"]').forEach(function(el) {+ const idx = parseInt(el.getAttribute('data-index'), 10);+ if (state.statements[idx]) state.statements[idx].sid = el.value;+ });+ document.querySelectorAll('.policy-stmt-effect[data-which="' + which + '"]:checked').forEach(function(el) {+ const idx = parseInt(el.getAttribute('data-index'), 10);+ if (state.statements[idx]) state.statements[idx].effect = el.value;+ });+ document.querySelectorAll('.policy-stmt-extras[data-which="' + which + '"]').forEach(function(el) {+ const idx = parseInt(el.getAttribute('data-index'), 10);+ if (state.statements[idx]) state.statements[idx].extras = el.value;+ });+ document.querySelectorAll('.policy-stmt-resource-mode[data-which="' + which + '"]').forEach(function(el) {+ const idx = parseInt(el.getAttribute('data-index'), 10);+ if (state.statements[idx]) state.statements[idx].resourceMode = el.value;+ });+ document.querySelectorAll('.policy-stmt-principal-mode[data-which="' + which + '"]').forEach(function(el) {+ const idx = parseInt(el.getAttribute('data-index'), 10);+ if (state.statements[idx]) state.statements[idx].principalMode = el.value;+ });+ document.querySelectorAll('.policy-list-item[data-which="' + which + '"]').forEach(function(el) {+ const idx = parseInt(el.getAttribute('data-index'), 10);+ const itemIdx = parseInt(el.getAttribute('data-item-index'), 10);+ const field = POLICY_LIST_FIELD_TO_STATE_KEY[el.getAttribute('data-field')] || 'resources';+ if (state.statements[idx] && state.statements[idx][field]) {+ state.statements[idx][field][itemIdx] = el.value;+ }+ });+ }++ // Serializes policyEditors[which] into the JSON textarea. Call before+ // switching to the JSON tab or before submitting, so the textarea always+ // reflects the editor's current contents.+ function commitPolicyEditorToTextarea(which) {+ commitPolicyEditorForm(which);+ const doc = policyEditorStateToDoc(policyEditors[which]);+ document.getElementById(policyTextareaId(which)).value = JSON.stringify(doc, null, 2);+ }++ // Parses the JSON textarea into policyEditors[which] and re-renders the+ // editor. Returns false (and shows an alert) if the JSON is invalid or a+ // statement's Effect isn't exactly "Allow"/"Deny", leaving the JSON tab+ // as the active one so the user can fix it.+ function commitPolicyTextareaToEditor(which) {+ const text = document.getElementById(policyTextareaId(which)).value;+ if (!text || !text.trim()) {+ policyEditors[which] = { version: '2012-10-17', statements: [], otherFields: {} };+ renderPolicyEditor(which);+ return true;+ }+ let doc;+ try {+ doc = JSON.parse(text);+ } catch (e) {+ showAlert('Invalid JSON in policy document: ' + e.message, 'error');+ return false;+ }+ let newState;+ try {+ newState = policyDocToEditorState(doc);+ } catch (e) {+ showAlert(e.message, 'error');+ return false;+ }+ policyEditors[which] = newState;+ renderPolicyEditor(which);+ return true;+ }++ function addPolicyStatement(which) {+ if (policyEditors[which].unparsed) {+ showAlert(POLICY_JSON_TAB_ONLY_MESSAGE, 'error');+ return;+ }+ commitPolicyEditorForm(which);+ policyEditors[which].statements.push({+ sid: '', effect: 'Allow', actions: [],+ resourceMode: 'Resource', resources: [],+ principalMode: 'Principal', principalValues: [], hasComplexPrincipal: false,+ extras: ''+ });+ renderPolicyEditor(which);+ }++ // True while the JSON tab (rather than the Editor tab) is the one+ // currently shown for `which`.+ function isPolicyJsonTabActive(which) {+ const jsonTabBtn = document.getElementById(which + 'PolicyJsonTabBtn');+ return !!(jsonTabBtn && jsonTabBtn.classList.contains('active'));+ }++ // Commits whichever tab is currently visible into the other side, so a+ // save/validate action always uses what the user is actually looking at+ // instead of silently overwriting it with stale state from the tab+ // they're not on. Returns false (after alerting the user) if that isn't+ // possible - e.g. invalid JSON on either side - so the caller can abort.+ function commitPolicyActiveTab(which) {+ if (isPolicyJsonTabActive(which)) {+ // The JSON tab is the source of truth right now; parse it back+ // into the structured editor to keep both in sync, but leave the+ // textarea's own text untouched.+ return commitPolicyTextareaToEditor(which);+ }+ if (policyEditors[which] && policyEditors[which].unparsed) {+ // The editor never held this document, so serializing it would+ // write an empty policy over whatever is in the JSON tab.+ showAlert(POLICY_JSON_TAB_ONLY_MESSAGE, 'error');+ return false;+ }+ try {+ commitPolicyEditorToTextarea(which);+ return true;+ } catch (e) {+ showAlert(e.message, 'error');+ return false;+ }+ }++ // The admin API's policy document carries only Version and Statement, so+ // any other top-level key (e.g. Id) is discarded server-side on save even+ // though the editor round-trips it between tabs. Warn before that happens+ // rather than letting the field vanish silently. Returns false if the+ // user cancels.+ function confirmPolicyFieldDiscard(which) {+ const otherFields = Object.keys((policyEditors[which] || {}).otherFields || {});+ if (otherFields.length === 0) return true;+ return confirm(+ 'The following top-level field(s) are not supported and will be dropped when this policy is saved: ' ++ otherFields.join(', ') + '.\n\nSave anyway?');+ }++ function setupPolicyEditor(which) {+ document.getElementById(which + 'PolicyAddStatementBtn').addEventListener('click', function() {+ addPolicyStatement(which);+ });++ const editorTabBtn = document.getElementById(which + 'PolicyEditorTabBtn');+ const jsonTabBtn = document.getElementById(which + 'PolicyJsonTabBtn');++ jsonTabBtn.addEventListener('show.bs.tab', function(event) {+ if (policyEditors[which].unparsed) {+ // The editor never held this document; serializing its empty+ // placeholder state would overwrite the textarea we are about+ // to show, which is the only copy of it.+ return;+ }+ try {+ commitPolicyEditorToTextarea(which);+ } catch (e) {+ showAlert(e.message, 'error');+ event.preventDefault();+ }+ });+ editorTabBtn.addEventListener('show.bs.tab', function(event) {+ if (!commitPolicyTextareaToEditor(which)) {+ event.preventDefault();+ }+ });++ const body = document.getElementById(policyEditorBodyId(which));+ body.addEventListener('change', function(event) {+ if (event.target.classList.contains('policy-stmt-resource-mode')) {+ // Redraw so the NotResource hint follows the selected mode.+ commitPolicyEditorForm(which);+ renderPolicyEditor(which);+ }+ });+ body.addEventListener('click', function(event) {+ const removeStmtBtn = event.target.closest('.policy-remove-statement-btn');+ if (removeStmtBtn) {+ commitPolicyEditorForm(which);+ const idx = parseInt(removeStmtBtn.getAttribute('data-index'), 10);+ policyEditors[which].statements.splice(idx, 1);+ renderPolicyEditor(which);+ return;+ }+ const addItemBtn = event.target.closest('.policy-add-list-item-btn');+ if (addItemBtn) {+ commitPolicyEditorForm(which);+ const idx = parseInt(addItemBtn.getAttribute('data-index'), 10);+ const field = POLICY_LIST_FIELD_TO_STATE_KEY[addItemBtn.getAttribute('data-field')] || 'resources';+ policyEditors[which].statements[idx][field].push('');+ renderPolicyEditor(which);+ return;+ }+ const removeItemBtn = event.target.closest('.policy-remove-list-item-btn');+ if (removeItemBtn) {+ commitPolicyEditorForm(which);+ const idx = parseInt(removeItemBtn.getAttribute('data-index'), 10);+ const itemIdx = parseInt(removeItemBtn.getAttribute('data-item-index'), 10);+ const field = POLICY_LIST_FIELD_TO_STATE_KEY[removeItemBtn.getAttribute('data-field')] || 'resources';+ policyEditors[which].statements[idx][field].splice(itemIdx, 1);+ renderPolicyEditor(which);+ }+ });++ // Populate the shared Resource datalist as the user types/focuses a+ // Resource field. Bootstrap's datalist filtering then narrows down+ // whatever set of options was last loaded for the current path stage.+ body.addEventListener('input', function(event) {+ const target = event.target;+ if (target.classList.contains('policy-list-item') && target.getAttribute('data-field') === 'resource') {+ updatePolicyResourceSuggestions(target);+ }+ });+ body.addEventListener('focusin', function(event) {+ const target = event.target;+ if (target.classList.contains('policy-list-item') && target.getAttribute('data-field') === 'resource') {+ updatePolicyResourceSuggestions(target);+ }+ });++ // Same idea for the shared Principal datalist: a flat, one-time+ // fetch (see loadPolicyPrincipalSuggestions), no per-segment logic+ // needed since users/roles aren't hierarchical like bucket paths.+ body.addEventListener('input', function(event) {+ const target = event.target;+ if (target.classList.contains('policy-list-item') && target.getAttribute('data-field') === 'principal') {+ updatePolicyPrincipalSuggestions();+ }+ });+ body.addEventListener('focusin', function(event) {+ const target = event.target;+ if (target.classList.contains('policy-list-item') && target.getAttribute('data-field') === 'principal') {+ updatePolicyPrincipalSuggestions();+ }+ });+ }++ // ------------------------------------------------------------------+ // Progressive Resource ARN autocomplete: suggests bucket names first+ // (arn:aws:s3:::bucket), then once a bucket + "/" is typed, suggests+ // arn:aws:s3:::bucket/* plus the direct subfolders one path segment at a+ // time (fetched from the server on demand, one directory level per+ // request, and cached per directory for the life of the page).+ // ------------------------------------------------------------------++ const POLICY_RESOURCE_ARN_PREFIX = 'arn:aws:s3:::';+ let policyBucketArnsPromise = null;+ const policyFolderListCache = new Map();++ function loadPolicyBucketArns() {+ if (!policyBucketArnsPromise) {+ policyBucketArnsPromise = fetch(basePath('/api/s3/buckets'))+ .then(function(r) { return r.ok ? r.json() : { buckets: [] }; })+ .then(function(data) {+ // Offer both the bucket itself and "every object in it",+ // since the latter is what most Resource entries actually need.+ return (data.buckets || []).reduce(function(acc, b) {+ const arn = POLICY_RESOURCE_ARN_PREFIX + b.name;+ acc.push(arn, arn + '/*');+ return acc;+ }, []);+ })+ .catch(function() { return []; });+ }+ return policyBucketArnsPromise;+ }++ function loadPolicyFolderNames(dirPath, prefix) {+ // Send the segment still being typed as a prefix so the filer does the+ // filtering: without it the server pages through every entry in the+ // directory, which on a bucket of flat object keys is the whole bucket.+ const key = dirPath + '\n' + prefix;+ if (!policyFolderListCache.has(key)) {+ policyFolderListCache.set(key, fetch(basePath('/api/files/list-folders?path=' + encodeURIComponent(dirPath) ++ '&prefix=' + encodeURIComponent(prefix)))+ .then(function(r) {+ if (!r.ok) throw new Error('list-folders request failed with status ' + r.status);+ return r.json();+ })+ .then(function(data) { return data.folders || []; })+ .catch(function() {+ // Don't let a transient failure permanently poison the+ // cache for this directory; let the next call retry.+ policyFolderListCache.delete(key);+ return [];+ }));+ }+ return policyFolderListCache.get(key);+ }++ // Figures out what stage of the ARN the user is currently typing:+ // still the bucket name ("bucket"), or a folder path segment after the+ // bucket ("folder", with dirPath being the filer directory to list and+ // arnPrefix being the ARN text to append suggestions onto).+ function policyResourcePathState(value) {+ value = value || '';+ if (value.indexOf(POLICY_RESOURCE_ARN_PREFIX) !== 0) {+ return { stage: 'bucket' };+ }+ const rest = value.slice(POLICY_RESOURCE_ARN_PREFIX.length);+ const segments = rest.split('/');+ if (segments.length === 1) {+ return { stage: 'bucket' };+ }+ const bucket = segments[0];+ const pathSegments = segments.slice(1, segments.length - 1);+ const suffix = pathSegments.length ? '/' + pathSegments.join('/') : '';+ return {+ stage: 'folder',+ dirPath: '/buckets/' + bucket + suffix,+ // The trailing, still-incomplete segment. The datalist narrows on+ // it too, but sending it keeps the server's listing bounded.+ prefix: segments[segments.length - 1],+ arnPrefix: POLICY_RESOURCE_ARN_PREFIX + bucket + suffix+ };+ }++ function renderPolicyDatalistOptions(datalist, values) {+ datalist.innerHTML = values.map(function(v) {+ return '<option value="' + escapeHtml(v) + '"></option>';+ }).join('');+ }++ function updatePolicyResourceSuggestions(inputEl) {+ const datalist = document.getElementById('policyResourceSuggestions');+ if (!datalist) return;+ const state = policyResourcePathState(inputEl.value);++ if (state.stage === 'bucket') {+ loadPolicyBucketArns().then(function(arns) {+ renderPolicyDatalistOptions(datalist, arns);+ });+ return;+ }++ loadPolicyFolderNames(state.dirPath, state.prefix).then(function(folders) {+ const options = [state.arnPrefix + '/*'];+ folders.forEach(function(name) {+ options.push(state.arnPrefix + '/' + name);+ });+ renderPolicyDatalistOptions(datalist, options);+ });+ }++ // ------------------------------------------------------------------+ // Principal autocomplete: a flat list of existing users and IAM roles,+ // fetched once from /api/principals and cached for the life of the page+ // (unlike Resource ARNs, users/roles have no hierarchy to drill into).+ // ------------------------------------------------------------------++ let policyPrincipalSuggestionsPromise = null;++ function loadPolicyPrincipalSuggestions() {+ if (!policyPrincipalSuggestionsPromise) {+ policyPrincipalSuggestionsPromise = fetch(basePath('/api/principals'))+ .then(function(r) { return r.ok ? r.json() : { principals: [] }; })+ .then(function(data) { return ['*'].concat(data.principals || []); })+ .catch(function() { return ['*']; });+ }+ return policyPrincipalSuggestionsPromise;+ }++ function updatePolicyPrincipalSuggestions() {+ const datalist = document.getElementById('policyPrincipalSuggestions');+ if (!datalist) return;+ loadPolicyPrincipalSuggestions().then(function(principals) {+ renderPolicyDatalistOptions(datalist, principals);+ });+ }++ // Fills the structured editor (and the JSON tab) with a sample policy,+ // regardless of which tab is currently active.+ const POLICY_SAMPLE_DOCUMENT = {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": [+ "s3:GetObject",+ "s3:PutObject"+ ],+ "Resource": [+ "arn:aws:s3:::my-bucket/*"+ ]+ }+ ]+ };++ function insertSamplePolicy(which) {+ policyEditors[which] = policyDocToEditorState(POLICY_SAMPLE_DOCUMENT);+ renderPolicyEditor(which);+ document.getElementById(policyTextareaId(which)).value = JSON.stringify(POLICY_SAMPLE_DOCUMENT, null, 2);+ }+// Event listeners for policy actionsdocument.addEventListener('DOMContentLoaded', function() {+ setupPolicyEditor('create');+ setupPolicyEditor('edit');+// View policy buttonsdocument.querySelectorAll('.view-policy-btn').forEach(button => {button.addEventListener('click', function() {@@ -316,7 +1101,7 @@ templ Policies(data dash.PoliciesData) {viewPolicy(policyName);});});-+// Edit policy buttonsdocument.querySelectorAll('.edit-policy-btn').forEach(button => {button.addEventListener('click', function() {@@ -324,7 +1109,7 @@ templ Policies(data dash.PoliciesData) {editPolicy(policyName);});});-+// Delete policy buttonsdocument.querySelectorAll('.delete-policy-btn').forEach(button => {button.addEventListener('click', function() {@@ -332,7 +1117,7 @@ templ Policies(data dash.PoliciesData) {deletePolicy(policyName);});});-+// Edit from view buttondocument.getElementById('editFromViewBtn').addEventListener('click', function() {if (currentPolicy) {@@ -341,20 +1126,30 @@ templ Policies(data dash.PoliciesData) {editPolicy(currentPolicy.name);}});++ // Reset the create modal's editor each time it's opened, so leftover+ // state from a previous (possibly cancelled) create doesn't leak in.+ document.getElementById('createPolicyModal').addEventListener('show.bs.modal', function() {+ document.getElementById('createPolicyForm').reset();+ policyEditors.create = { version: '2012-10-17', statements: [], otherFields: {} };+ renderPolicyEditor('create');+ const editorTab = bootstrap.Tab.getOrCreateInstance(document.getElementById('createPolicyEditorTabBtn'));+ editorTab.show();+ });});-+function createPolicy() {- const form = document.getElementById('createPolicyForm');- const formData = new FormData(form);-- const policyName = formData.get('name');- const policyDocumentText = formData.get('document');-+ if (!commitPolicyActiveTab('create')) return;+ if (!confirmPolicyFieldDiscard('create')) return;++ const policyName = document.getElementById('policyName').value;+ const policyDocumentText = document.getElementById('policyDocument').value;+if (!policyName || !policyDocumentText) {showAlert('Please fill in all required fields', 'warning');return;}-+let policyDocument;try {policyDocument = JSON.parse(policyDocumentText);@@ -362,41 +1157,45 @@ templ Policies(data dash.PoliciesData) {showAlert('Invalid JSON in policy document: ' + e.message, 'error');return;}-+const requestData = {name: policyName,document: policyDocument};-- fetch(basePath('/api/object-store/policies'), {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify(requestData)- })- .then(response => response.json())- .then(data => {- if (data.success) {- showAlert('Policy created successfully!', 'success');- const modal = bootstrap.Modal.getInstance(document.getElementById('createPolicyModal'));- if (modal) modal.hide();- location.reload(); // Refresh the page to show the new policy- } else {- showAlert('Error creating policy: ' + (data.error || 'Unknown error'), 'error');- }- })- .catch(error => {- console.error('Error:', error);- showAlert('Error creating policy: ' + error.message, 'error');++ validatePolicyJSON(policyDocumentText, true).then(valid => {+ if (!valid) return;++ fetch(basePath('/api/object-store/policies'), {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(requestData)+ })+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ showAlert('Policy created successfully!', 'success');+ const modal = bootstrap.Modal.getInstance(document.getElementById('createPolicyModal'));+ if (modal) modal.hide();+ location.reload(); // Refresh the page to show the new policy+ } else {+ showAlert('Error creating policy: ' + (data.error || 'Unknown error'), 'error');+ }+ })+ .catch(error => {+ console.error('Error:', error);+ showAlert('Error creating policy: ' + error.message, 'error');+ });});}-+function viewPolicy(policyName) {// Show the modal firstconst modal = new bootstrap.Modal(document.getElementById('viewPolicyModal'));modal.show();-+// Reset content to loading statedocument.getElementById('viewPolicyContent').innerHTML = `<div class="text-center">@@ -406,7 +1205,7 @@ templ Policies(data dash.PoliciesData) {<p class="mt-2">Loading policy...</p></div>`;-+// Fetch policy datafetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName))).then(response => {@@ -429,70 +1228,104 @@ templ Policies(data dash.PoliciesData) {`;});}-+function displayPolicyDetails(policy) {const content = document.getElementById('viewPolicyContent');-++ // Escapes a policy value for display, whether it's carried as a+ // single value or a list, and whatever type it turns out to be.+ function escapedJoin(list) {+ if (list === undefined || list === null) return '';+ return (Array.isArray(list) ? list : [list]).map(function(v) { return escapeHtml(String(v)); }).join(', ');+ }++ // Summarizes a Principal/NotPrincipal value for read-only display,+ // regardless of shape (bare string/array, or a {"Type": ...} object -+ // possibly with several type keys), since the View modal must stay+ // correct even for forms the structured editor doesn't model.+ function principalSummary(value) {+ if (value === undefined || value === null) return '';+ if (Array.isArray(value)) return escapedJoin(value);+ if (typeof value === 'object') {+ return Object.keys(value).map(function(key) {+ const v = value[key];+ return escapeHtml(key) + ': ' + escapedJoin(v);+ }).join('; ');+ }+ return escapeHtml(String(value));+ }+let statementsHtml = '';if (policy.document && policy.document.Statement) {statementsHtml = policy.document.Statement.map((stmt, index) => `<div class="card mb-2"><div class="card-header py-2">- <h6 class="mb-0">Statement ${index + 1}</h6>+ <h6 class="mb-0">Statement ${index + 1}${stmt.Sid ? ' — ' + escapeHtml(stmt.Sid) : ''}</h6></div><div class="card-body py-2"><div class="row"><div class="col-md-6">- <strong>Effect:</strong>- <span class="badge ${stmt.Effect === 'Allow' ? 'bg-success' : 'bg-danger'}">${stmt.Effect}</span>+ <strong>Effect:</strong>+ <span class="badge ${stmt.Effect === 'Allow' ? 'bg-success' : 'bg-danger'}">${escapedJoin(stmt.Effect)}</span></div><div class="col-md-6">- <strong>Actions:</strong> ${Array.isArray(stmt.Action) ? stmt.Action.join(', ') : stmt.Action}+ <strong>Actions:</strong> ${escapedJoin(stmt.Action)}</div></div><div class="row mt-2"><div class="col-12">- <strong>Resources:</strong> ${Array.isArray(stmt.Resource) ? stmt.Resource.join(', ') : stmt.Resource}+ ${stmt.NotResource+ ? '<strong>NotResource (excluded):</strong> ' + escapedJoin(stmt.NotResource)+ : '<strong>Resource:</strong> ' + escapedJoin(stmt.Resource)}</div></div>+ ${(stmt.Principal || stmt.NotPrincipal)+ ? '<div class="row mt-2"><div class="col-12">' ++ (stmt.NotPrincipal+ ? '<strong>NotPrincipal (excluded):</strong> ' + principalSummary(stmt.NotPrincipal)+ : '<strong>Principal:</strong> ' + principalSummary(stmt.Principal)) ++ '</div></div>'+ : ''}</div></div>`).join('');}-+content.innerHTML = `<div class="row mb-3"><div class="col-md-6">- <strong>Policy Name:</strong> ${policy.name || 'Unknown'}+ <strong>Policy Name:</strong> ${escapedJoin(policy.name || 'Unknown')}</div><div class="col-md-6">- <strong>Version:</strong> <span class="badge bg-info">${policy.document?.Version || 'Unknown'}</span>+ <strong>Version:</strong> <span class="badge bg-info">${escapedJoin(policy.document?.Version || 'Unknown')}</span></div></div>-+<div class="mb-3"><strong>Statements:</strong><div class="mt-2">${statementsHtml || '<p class="text-muted">No statements found</p>'}</div></div>-+<div class="mb-3"><strong>Raw Policy Document:</strong>- <pre class="bg-light p-3 border rounded mt-2"><code>${JSON.stringify(policy.document, null, 2)}</code></pre>+ <pre class="bg-light p-3 border rounded mt-2"><code>${escapeHtml(JSON.stringify(policy.document, null, 2))}</code></pre></div>`;}-+function editPolicy(policyName) {// Show the modal firstconst modal = new bootstrap.Modal(document.getElementById('editPolicyModal'));modal.show();-+// Set policy namedocument.getElementById('editPolicyName').value = policyName;document.getElementById('editPolicyDocument').value = 'Loading...';-+ policyEditors.edit = { version: '2012-10-17', statements: [], otherFields: {} };+ renderPolicyEditor('edit');+// Fetch policy datafetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName))).then(response => {@@ -504,6 +1337,23 @@ templ Policies(data dash.PoliciesData) {.then(policy => {currentPolicy = policy;document.getElementById('editPolicyDocument').value = JSON.stringify(policy.document, null, 2);+ let state;+ try {+ state = policyDocToEditorState(policy.document);+ } catch (e) {+ // Valid JSON the structured editor can't model. The JSON tab+ // exists for exactly this, so hand the document over to it+ // rather than closing the modal on the only view of it.+ policyEditors.edit = { version: '2012-10-17', statements: [], otherFields: {}, unparsed: true };+ renderPolicyEditor('edit');+ showAlert(e.message + '. ' + POLICY_JSON_TAB_ONLY_MESSAGE, 'error');+ bootstrap.Tab.getOrCreateInstance(document.getElementById('editPolicyJsonTabBtn')).show();+ return;+ }+ policyEditors.edit = state;+ renderPolicyEditor('edit');+ const editorTab = bootstrap.Tab.getOrCreateInstance(document.getElementById('editPolicyEditorTabBtn'));+ editorTab.show();}).catch(error => {console.error('Error:', error);@@ -512,16 +1362,19 @@ templ Policies(data dash.PoliciesData) {if (editModal) editModal.hide();});}-+function updatePolicy() {+ if (!commitPolicyActiveTab('edit')) return;+ if (!confirmPolicyFieldDiscard('edit')) return;+const policyName = document.getElementById('editPolicyName').value;const policyDocumentText = document.getElementById('editPolicyDocument').value;-+if (!policyName || !policyDocumentText) {showAlert('Please fill in all required fields', 'warning');return;}-+let policyDocument;try {policyDocument = JSON.parse(policyDocumentText);@@ -529,111 +1382,88 @@ templ Policies(data dash.PoliciesData) {showAlert('Invalid JSON in policy document: ' + e.message, 'error');return;}-+const requestData = {document: policyDocument};-- fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {- method: 'PUT',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify(requestData)- })- .then(response => response.json())- .then(data => {- if (data.success) {- showAlert('Policy updated successfully!', 'success');- const modal = bootstrap.Modal.getInstance(document.getElementById('editPolicyModal'));- if (modal) modal.hide();- location.reload(); // Refresh the page to show the updated policy- } else {- showAlert('Error updating policy: ' + (data.error || 'Unknown error'), 'error');- }- })- .catch(error => {- console.error('Error:', error);- showAlert('Error updating policy: ' + error.message, 'error');- });- }-- function insertSamplePolicy() {- const samplePolicy = {- "Version": "2012-10-17",- "Statement": [- {- "Effect": "Allow",- "Action": [- "s3:GetObject",- "s3:PutObject"- ],- "Resource": [- "arn:aws:s3:::my-bucket/*"- ]- }- ]- };-- document.getElementById('policyDocument').value = JSON.stringify(samplePolicy, null, 2);- }-- function insertSamplePolicyEdit() {- const samplePolicy = {- "Version": "2012-10-17",- "Statement": [- {- "Effect": "Allow",- "Action": [- "s3:GetObject",- "s3:PutObject"- ],- "Resource": [- "arn:aws:s3:::my-bucket/*"- ]++ validatePolicyJSON(policyDocumentText, true).then(valid => {+ if (!valid) return;++ fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {+ method: 'PUT',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(requestData)+ })+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ showAlert('Policy updated successfully!', 'success');+ const modal = bootstrap.Modal.getInstance(document.getElementById('editPolicyModal'));+ if (modal) modal.hide();+ location.reload(); // Refresh the page to show the updated policy+ } else {+ showAlert('Error updating policy: ' + (data.error || 'Unknown error'), 'error');}- ]- };-- document.getElementById('editPolicyDocument').value = JSON.stringify(samplePolicy, null, 2);- }-- function validatePolicyDocument() {- const policyText = document.getElementById('policyDocument').value;- validatePolicyJSON(policyText);+ })+ .catch(error => {+ console.error('Error:', error);+ showAlert('Error updating policy: ' + error.message, 'error');+ });+ });}-- function validateEditPolicyDocument() {- const policyText = document.getElementById('editPolicyDocument').value;++ function validatePolicyDocument(which) {+ if (!commitPolicyActiveTab(which)) return;+ const policyText = document.getElementById(policyTextareaId(which)).value;validatePolicyJSON(policyText);}-- function validatePolicyJSON(policyText) {++ // Runs a policy document past the server's validator. Resolves to true+ // when it passes, and to false after alerting the user when it doesn't.+ // `quiet` suppresses the success alert for callers that go on to report+ // an outcome of their own.+ function validatePolicyJSON(policyText, quiet) {if (!policyText) {showAlert('Please enter a policy document first', 'warning');- return;+ return Promise.resolve(false);}-++ let policyDocument;try {- const policy = JSON.parse(policyText);-- // Basic validation- if (!policy.Version) {- showAlert('Policy must have a Version field', 'error');- return;- }-- if (!policy.Statement || !Array.isArray(policy.Statement)) {- showAlert('Policy must have a Statement array', 'error');- return;- }-- showAlert('Policy document is valid JSON!', 'success');+ policyDocument = JSON.parse(policyText);} catch (e) {showAlert('Invalid JSON: ' + e.message, 'error');+ return Promise.resolve(false);}++ return fetch(basePath('/api/object-store/policies/validate'), {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ document: policyDocument })+ })+ .then(response => response.json().then(data => ({ ok: response.ok, data })))+ .then(({ ok, data }) => {+ if (ok && data.valid) {+ if (!quiet) {+ showAlert(data.message || 'Policy document is valid!', 'success');+ }+ return true;+ }+ showAlert('Invalid policy: ' + (data.error || 'unknown error'), 'error');+ return false;+ })+ .catch(error => {+ console.error('Error:', error);+ showAlert('Error validating policy: ' + error.message, 'error');+ return false;+ });}-+function deletePolicy(policyName) {showDeleteConfirm(policyName, function() {fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {@@ -655,4 +1485,4 @@ templ Policies(data dash.PoliciesData) {});}</script>-}\ No newline at end of file+}diff --git a/weed/admin/view/app/policies_templ.go b/weed/admin/view/app/policies_templ.goindex abee882abb..5b93803b2f 100644--- a/weed/admin/view/app/policies_templ.go+++ b/weed/admin/view/app/policies_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.1001+// templ: version: v0.3.1020package app//lint:file-ignore SA4006 This context is only used if a nested component is present.@@ -41,7 +41,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var2 stringtempl_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPolicies))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 34, Col: 74}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 34, Col: 74}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))if templ_7745c5c3_Err != nil {@@ -54,7 +54,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var3 stringtempl_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPolicies))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 54, Col: 74}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 54, Col: 74}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))if templ_7745c5c3_Err != nil {@@ -67,7 +67,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var4 stringtempl_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 74, Col: 69}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 74, Col: 69}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))if templ_7745c5c3_Err != nil {@@ -85,7 +85,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var5 stringtempl_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 123, Col: 68}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 123, Col: 68}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))if templ_7745c5c3_Err != nil {@@ -98,7 +98,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var6 stringtempl_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Document.Version)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 126, Col: 100}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 126, Col: 100}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))if templ_7745c5c3_Err != nil {@@ -111,7 +111,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var7 stringtempl_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d statements", len(policy.Document.Statement)))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 129, Col: 142}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 129, Col: 142}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))if templ_7745c5c3_Err != nil {@@ -124,7 +124,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var8 stringtempl_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(policy.CreatedAt.Format("2006-01-02 15:04"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 132, Col: 118}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 132, Col: 118}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))if templ_7745c5c3_Err != nil {@@ -137,7 +137,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var9 stringtempl_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(policy.UpdatedAt.Format("2006-01-02 15:04"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 135, Col: 118}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 135, Col: 118}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))if templ_7745c5c3_Err != nil {@@ -148,11 +148,11 @@ func Policies(data dash.PoliciesData) templ.Component {return templ_7745c5c3_Err}var templ_7745c5c3_Var10 string- templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)+ templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.ResolveAttributeValue(policy.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 139, Col: 168}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 139, Col: 168}}- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var10)if templ_7745c5c3_Err != nil {return templ_7745c5c3_Err}@@ -161,11 +161,11 @@ func Policies(data dash.PoliciesData) templ.Component {return templ_7745c5c3_Err}var templ_7745c5c3_Var11 string- templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)+ templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.ResolveAttributeValue(policy.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 142, Col: 171}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 142, Col: 171}}- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var11)if templ_7745c5c3_Err != nil {return templ_7745c5c3_Err}@@ -174,11 +174,11 @@ func Policies(data dash.PoliciesData) templ.Component {return templ_7745c5c3_Err}var templ_7745c5c3_Var12 string- templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)+ templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.ResolveAttributeValue(policy.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 145, Col: 174}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 145, Col: 174}}- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var12)if templ_7745c5c3_Err != nil {return templ_7745c5c3_Err}@@ -193,7 +193,30 @@ func Policies(data dash.PoliciesData) templ.Component {return templ_7745c5c3_Err}}- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div></div></div><!-- Create Policy Modal --><div class=\"modal fade\" id=\"createPolicyModal\" tabindex=\"-1\" aria-labelledby=\"createPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Create IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"createPolicyForm\"><div class=\"mb-3\"><label for=\"policyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"policyName\" name=\"name\" required placeholder=\"e.g., S3ReadOnlyPolicy\"><div class=\"form-text\">Enter a unique name for this policy (alphanumeric and underscores only)</div></div><div class=\"mb-3\"><label for=\"policyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"policyDocument\" name=\"document\" rows=\"15\" required placeholder=\"Enter IAM policy JSON document...\"></textarea><div class=\"form-text\">Enter the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy()\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createPolicy()\"><i class=\"fas fa-plus me-1\"></i>Create Policy</button></div></div></div></div><!-- View Policy Modal --><div class=\"modal fade\" id=\"viewPolicyModal\" tabindex=\"-1\" aria-labelledby=\"viewPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"viewPolicyModalLabel\"><i class=\"fas fa-eye me-2\"></i>View IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"viewPolicyContent\"><div class=\"text-center\"><div class=\"spinner-border\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><p class=\"mt-2\">Loading policy...</p></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button> <button type=\"button\" class=\"btn btn-primary\" id=\"editFromViewBtn\"><i class=\"fas fa-edit me-1\"></i>Edit Policy</button></div></div></div></div><!-- Edit Policy Modal --><div class=\"modal fade\" id=\"editPolicyModal\" tabindex=\"-1\" aria-labelledby=\"editPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"editPolicyModalLabel\"><i class=\"fas fa-edit me-2\"></i>Edit IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"editPolicyForm\"><div class=\"mb-3\"><label for=\"editPolicyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"editPolicyName\" name=\"name\" readonly><div class=\"form-text\">Policy name cannot be changed</div></div><div class=\"mb-3\"><label for=\"editPolicyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"editPolicyDocument\" name=\"document\" rows=\"15\" required></textarea><div class=\"form-text\">Edit the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicyEdit()\"><i class=\"fas fa-file-alt me-1\"></i>Reset to Sample</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validateEditPolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"updatePolicy()\"><i class=\"fas fa-save me-1\"></i>Save Changes</button></div></div></div></div><!-- JavaScript for Policy Management --><script>\n // Current policy being viewed/edited\n let currentPolicy = null;\n \n // Event listeners for policy actions\n document.addEventListener('DOMContentLoaded', function() {\n // View policy buttons\n document.querySelectorAll('.view-policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const policyName = this.getAttribute('data-policy-name');\n viewPolicy(policyName);\n });\n });\n \n // Edit policy buttons\n document.querySelectorAll('.edit-policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const policyName = this.getAttribute('data-policy-name');\n editPolicy(policyName);\n });\n });\n \n // Delete policy buttons\n document.querySelectorAll('.delete-policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const policyName = this.getAttribute('data-policy-name');\n deletePolicy(policyName);\n });\n });\n \n // Edit from view button\n document.getElementById('editFromViewBtn').addEventListener('click', function() {\n if (currentPolicy) {\n const viewModal = bootstrap.Modal.getInstance(document.getElementById('viewPolicyModal'));\n if (viewModal) viewModal.hide();\n editPolicy(currentPolicy.name);\n }\n });\n });\n \n function createPolicy() {\n const form = document.getElementById('createPolicyForm');\n const formData = new FormData(form);\n \n const policyName = formData.get('name');\n const policyDocumentText = formData.get('document');\n \n if (!policyName || !policyDocumentText) {\n showAlert('Please fill in all required fields', 'warning');\n return;\n }\n \n let policyDocument;\n try {\n policyDocument = JSON.parse(policyDocumentText);\n } catch (e) {\n showAlert('Invalid JSON in policy document: ' + e.message, 'error');\n return;\n }\n \n const requestData = {\n name: policyName,\n document: policyDocument\n };\n \n fetch(basePath('/api/object-store/policies'), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestData)\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Policy created successfully!', 'success');\n const modal = bootstrap.Modal.getInstance(document.getElementById('createPolicyModal'));\n if (modal) modal.hide();\n location.reload(); // Refresh the page to show the new policy\n } else {\n showAlert('Error creating policy: ' + (data.error || 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error creating policy: ' + error.message, 'error');\n });\n }\n \n function viewPolicy(policyName) {\n // Show the modal first\n const modal = new bootstrap.Modal(document.getElementById('viewPolicyModal'));\n modal.show();\n \n // Reset content to loading state\n document.getElementById('viewPolicyContent').innerHTML = `\n <div class=\"text-center\">\n <div class=\"spinner-border\" role=\"status\">\n <span class=\"visually-hidden\">Loading...</span>\n </div>\n <p class=\"mt-2\">Loading policy...</p>\n </div>\n `;\n \n // Fetch policy data\n fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)))\n .then(response => {\n if (!response.ok) {\n throw new Error('Policy not found');\n }\n return response.json();\n })\n .then(policy => {\n currentPolicy = policy;\n displayPolicyDetails(policy);\n })\n .catch(error => {\n console.error('Error:', error);\n document.getElementById('viewPolicyContent').innerHTML = `\n <div class=\"alert alert-danger\" role=\"alert\">\n <i class=\"fas fa-exclamation-triangle me-2\"></i>\n Error loading policy: ${error.message}\n </div>\n `;\n });\n }\n \n function displayPolicyDetails(policy) {\n const content = document.getElementById('viewPolicyContent');\n \n let statementsHtml = '';\n if (policy.document && policy.document.Statement) {\n statementsHtml = policy.document.Statement.map((stmt, index) => `\n <div class=\"card mb-2\">\n <div class=\"card-header py-2\">\n <h6 class=\"mb-0\">Statement ${index + 1}</h6>\n </div>\n <div class=\"card-body py-2\">\n <div class=\"row\">\n <div class=\"col-md-6\">\n <strong>Effect:</strong> \n <span class=\"badge ${stmt.Effect === 'Allow' ? 'bg-success' : 'bg-danger'}\">${stmt.Effect}</span>\n </div>\n <div class=\"col-md-6\">\n <strong>Actions:</strong> ${Array.isArray(stmt.Action) ? stmt.Action.join(', ') : stmt.Action}\n </div>\n </div>\n <div class=\"row mt-2\">\n <div class=\"col-12\">\n <strong>Resources:</strong> ${Array.isArray(stmt.Resource) ? stmt.Resource.join(', ') : stmt.Resource}\n </div>\n </div>\n </div>\n </div>\n `).join('');\n }\n \n content.innerHTML = `\n <div class=\"row mb-3\">\n <div class=\"col-md-6\">\n <strong>Policy Name:</strong> ${policy.name || 'Unknown'}\n </div>\n <div class=\"col-md-6\">\n <strong>Version:</strong> <span class=\"badge bg-info\">${policy.document?.Version || 'Unknown'}</span>\n </div>\n </div>\n \n <div class=\"mb-3\">\n <strong>Statements:</strong>\n <div class=\"mt-2\">\n ${statementsHtml || '<p class=\"text-muted\">No statements found</p>'}\n </div>\n </div>\n \n <div class=\"mb-3\">\n <strong>Raw Policy Document:</strong>\n <pre class=\"bg-light p-3 border rounded mt-2\"><code>${JSON.stringify(policy.document, null, 2)}</code></pre>\n </div>\n `;\n }\n \n function editPolicy(policyName) {\n // Show the modal first\n const modal = new bootstrap.Modal(document.getElementById('editPolicyModal'));\n modal.show();\n \n // Set policy name\n document.getElementById('editPolicyName').value = policyName;\n document.getElementById('editPolicyDocument').value = 'Loading...';\n \n // Fetch policy data\n fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)))\n .then(response => {\n if (!response.ok) {\n throw new Error('Policy not found');\n }\n return response.json();\n })\n .then(policy => {\n currentPolicy = policy;\n document.getElementById('editPolicyDocument').value = JSON.stringify(policy.document, null, 2);\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error loading policy for editing: ' + error.message, 'error');\n const editModal = bootstrap.Modal.getInstance(document.getElementById('editPolicyModal'));\n if (editModal) editModal.hide();\n });\n }\n \n function updatePolicy() {\n const policyName = document.getElementById('editPolicyName').value;\n const policyDocumentText = document.getElementById('editPolicyDocument').value;\n \n if (!policyName || !policyDocumentText) {\n showAlert('Please fill in all required fields', 'warning');\n return;\n }\n \n let policyDocument;\n try {\n policyDocument = JSON.parse(policyDocumentText);\n } catch (e) {\n showAlert('Invalid JSON in policy document: ' + e.message, 'error');\n return;\n }\n \n const requestData = {\n document: policyDocument\n };\n \n fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestData)\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Policy updated successfully!', 'success');\n const modal = bootstrap.Modal.getInstance(document.getElementById('editPolicyModal'));\n if (modal) modal.hide();\n location.reload(); // Refresh the page to show the updated policy\n } else {\n showAlert('Error updating policy: ' + (data.error || 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error updating policy: ' + error.message, 'error');\n });\n }\n \n function insertSamplePolicy() {\n const samplePolicy = {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::my-bucket/*\"\n ]\n }\n ]\n };\n \n document.getElementById('policyDocument').value = JSON.stringify(samplePolicy, null, 2);\n }\n \n function insertSamplePolicyEdit() {\n const samplePolicy = {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::my-bucket/*\"\n ]\n }\n ]\n };\n \n document.getElementById('editPolicyDocument').value = JSON.stringify(samplePolicy, null, 2);\n }\n \n function validatePolicyDocument() {\n const policyText = document.getElementById('policyDocument').value;\n validatePolicyJSON(policyText);\n }\n \n function validateEditPolicyDocument() {\n const policyText = document.getElementById('editPolicyDocument').value;\n validatePolicyJSON(policyText);\n }\n \n function validatePolicyJSON(policyText) {\n if (!policyText) {\n showAlert('Please enter a policy document first', 'warning');\n return;\n }\n \n try {\n const policy = JSON.parse(policyText);\n \n // Basic validation\n if (!policy.Version) {\n showAlert('Policy must have a Version field', 'error');\n return;\n }\n \n if (!policy.Statement || !Array.isArray(policy.Statement)) {\n showAlert('Policy must have a Statement array', 'error');\n return;\n }\n \n showAlert('Policy document is valid JSON!', 'success');\n } catch (e) {\n showAlert('Invalid JSON: ' + e.message, 'error');\n }\n }\n \n function deletePolicy(policyName) {\n showDeleteConfirm(policyName, function() {\n fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {\n method: 'DELETE'\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Policy deleted successfully!', 'success');\n location.reload();\n } else {\n showAlert('Error deleting policy: ' + (data.error || 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error deleting policy: ' + error.message, 'error');\n });\n });\n }\n </script>")+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div></div></div><style>\n /* Groups a statement's Sid/Effect and its Action/Resource/Principal\n sections in the structured policy editor. Plain <fieldset>/<legend>\n render fine natively, but Bootstrap's form reset stretches <legend> to\n the fieldset's full width (float: left; width: 100%), which loses the\n usual \"notch in the border\" look and makes the label bar as wide as\n the card. Undo just that here so the legend hugs its content instead.\n */\n .policy-stmt-fieldset {\n border: 1px solid var(--bs-border-color, #dee2e6);\n border-radius: 0.375rem;\n padding: 0 0.75rem 0.75rem;\n margin: 0.75rem 0 0;\n }\n .policy-stmt-legend {\n float: none;\n width: auto;\n max-width: 100%;\n padding: 0 0.5rem;\n margin: 0 0 0.25rem;\n font-size: 0.8125rem;\n font-weight: 600;\n color: var(--bs-secondary-color, #6c757d);\n }\n </style><!-- Datalist of suggested action names, shared by the create/edit editors --><datalist id=\"policyActionSuggestions\">")+ if templ_7745c5c3_Err != nil {+ return templ_7745c5c3_Err+ }+ for _, action := range PolicyActionSuggestions {+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "<option value=\"")+ if templ_7745c5c3_Err != nil {+ return templ_7745c5c3_Err+ }+ var templ_7745c5c3_Var13 string+ templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.ResolveAttributeValue(action)+ if templ_7745c5c3_Err != nil {+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 204, Col: 33}+ }+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var13)+ if templ_7745c5c3_Err != nil {+ return templ_7745c5c3_Err+ }+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "\"></option>")+ if templ_7745c5c3_Err != nil {+ return templ_7745c5c3_Err+ }+ }+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</datalist><!-- Populated dynamically as the user types in a Resource field: bucket\n names first, then subfolders one path segment at a time. See\n updatePolicyResourceSuggestions() below. --><datalist id=\"policyResourceSuggestions\"></datalist><!-- Populated dynamically as the user types/focuses a Principal field:\n existing users and IAM roles, fetched once from /api/principals. See\n updatePolicyPrincipalSuggestions() below. --><datalist id=\"policyPrincipalSuggestions\"></datalist><!-- Create Policy Modal --><div class=\"modal fade\" id=\"createPolicyModal\" tabindex=\"-1\" aria-labelledby=\"createPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Create IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"createPolicyForm\"><div class=\"mb-3\"><label for=\"policyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"policyName\" name=\"name\" required placeholder=\"e.g., S3ReadOnlyPolicy\"><div class=\"form-text\">Enter a unique name for this policy (alphanumeric and underscores only)</div></div><ul class=\"nav nav-tabs\" role=\"tablist\"><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link active\" id=\"createPolicyEditorTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#createPolicyEditorTab\">Editor</button></li><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link\" id=\"createPolicyJsonTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#createPolicyJsonTab\">JSON</button></li></ul><div class=\"tab-content border border-top-0 rounded-bottom p-3 mb-3\"><div class=\"tab-pane fade show active\" id=\"createPolicyEditorTab\"><div id=\"createPolicyEditorBody\"></div><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"createPolicyAddStatementBtn\"><i class=\"fas fa-plus me-1\"></i>Add statement</button></div><div class=\"tab-pane fade\" id=\"createPolicyJsonTab\"><textarea class=\"form-control\" id=\"policyDocument\" name=\"document\" rows=\"15\" placeholder=\"Enter IAM policy JSON document...\"></textarea><div class=\"form-text\">Enter the policy document in AWS IAM JSON format</div></div></div><div class=\"mb-3 d-flex justify-content-between\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy('create')\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button> <button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument('create')\"><i class=\"fas fa-check me-1\"></i>Validate</button></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createPolicy()\"><i class=\"fas fa-plus me-1\"></i>Create Policy</button></div></div></div></div><!-- View Policy Modal --><div class=\"modal fade\" id=\"viewPolicyModal\" tabindex=\"-1\" aria-labelledby=\"viewPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"viewPolicyModalLabel\"><i class=\"fas fa-eye me-2\"></i>View IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"viewPolicyContent\"><div class=\"text-center\"><div class=\"spinner-border\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><p class=\"mt-2\">Loading policy...</p></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button> <button type=\"button\" class=\"btn btn-primary\" id=\"editFromViewBtn\"><i class=\"fas fa-edit me-1\"></i>Edit Policy</button></div></div></div></div><!-- Edit Policy Modal --><div class=\"modal fade\" id=\"editPolicyModal\" tabindex=\"-1\" aria-labelledby=\"editPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"editPolicyModalLabel\"><i class=\"fas fa-edit me-2\"></i>Edit IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"editPolicyForm\"><div class=\"mb-3\"><label for=\"editPolicyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"editPolicyName\" name=\"name\" readonly><div class=\"form-text\">Policy name cannot be changed</div></div><ul class=\"nav nav-tabs\" role=\"tablist\"><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link active\" id=\"editPolicyEditorTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#editPolicyEditorTab\">Editor</button></li><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link\" id=\"editPolicyJsonTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#editPolicyJsonTab\">JSON</button></li></ul><div class=\"tab-content border border-top-0 rounded-bottom p-3 mb-3\"><div class=\"tab-pane fade show active\" id=\"editPolicyEditorTab\"><div id=\"editPolicyEditorBody\"></div><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"editPolicyAddStatementBtn\"><i class=\"fas fa-plus me-1\"></i>Add statement</button></div><div class=\"tab-pane fade\" id=\"editPolicyJsonTab\"><textarea class=\"form-control\" id=\"editPolicyDocument\" name=\"document\" rows=\"15\"></textarea><div class=\"form-text\">Edit the policy document in AWS IAM JSON format</div></div></div><div class=\"mb-3 d-flex justify-content-between\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy('edit')\"><i class=\"fas fa-file-alt me-1\"></i>Reset to Sample</button> <button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument('edit')\"><i class=\"fas fa-check me-1\"></i>Validate</button></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"updatePolicy()\"><i class=\"fas fa-save me-1\"></i>Save Changes</button></div></div></div></div><!-- JavaScript for Policy Management --><script>\n // Current policy being viewed/edited\n let currentPolicy = null;\n\n // Structured-editor state, one entry per modal (\"create\" / \"edit\"). Each\n // entry is { version, statements: [{ sid, effect, actions, resources, extras }] }.\n // \"extras\" holds the JSON text of any statement fields the structured\n // editor doesn't expose (Principal, NotPrincipal, NotResource, Condition,\n // or any future/unknown key), so they round-trip untouched.\n let policyEditors = {\n create: { version: '2012-10-17', statements: [], otherFields: {} },\n edit: { version: '2012-10-17', statements: [], otherFields: {} }\n };\n\n const POLICY_STATEMENT_KNOWN_KEYS = ['Sid', 'Effect', 'Action', 'Resource', 'NotResource'];\n\n // Shown for a policy that parsed as JSON but that the structured editor\n // can't represent, so its editor state carries { unparsed: true } and the\n // document only ever lives in the JSON tab.\n const POLICY_JSON_TAB_ONLY_MESSAGE = 'This policy can only be edited on the JSON tab.';\n\n // Maps a policy-list-item's data-field attribute to the editor-state\n // array it belongs to.\n const POLICY_LIST_FIELD_TO_STATE_KEY = { action: 'actions', resource: 'resources', principal: 'principalValues' };\n\n function policyTextareaId(which) {\n return which === 'create' ? 'policyDocument' : 'editPolicyDocument';\n }\n\n function policyEditorBodyId(which) {\n return which + 'PolicyEditorBody';\n }\n\n function normalizeToStringArray(value) {\n if (value === undefined || value === null) return [];\n // Coerce: these feed escapeHtml, which calls text.replace, and a\n // policy is free to carry a number or a boolean here.\n if (Array.isArray(value)) return value.map(String);\n return [String(value)];\n }\n\n const POLICY_DOCUMENT_KNOWN_KEYS = ['Version', 'Statement'];\n\n // Converts a policy document (as parsed from JSON) into editor state.\n //\n // Top-level keys the editor doesn't model (e.g. Id) are kept verbatim in\n // state.otherFields and merged back on serialization, so a round-trip\n // through the Editor tab doesn't rewrite text the user typed in the JSON\n // tab. The admin API's PolicyDocument only carries Version and Statement,\n // so such fields are still dropped by the server on save; see\n // confirmPolicyFieldDiscard, which warns the user before that happens.\n function policyDocToEditorState(doc) {\n if (doc === null || typeof doc !== 'object') {\n // null or a bare scalar (string/number/boolean) can't represent a\n // policy document; treating it as \"zero statements\" would hide\n // from the user that their input wasn't actually a document.\n throw new Error('Policy document must be a JSON object (got ' + JSON.stringify(doc) + ')');\n }\n const state = { version: doc.Version || '2012-10-17', statements: [], otherFields: {} };\n if (!Array.isArray(doc)) {\n Object.keys(doc).forEach(function(key) {\n if (POLICY_DOCUMENT_KNOWN_KEYS.indexOf(key) === -1) {\n state.otherFields[key] = doc[key];\n }\n });\n }\n const rawStatements = doc && doc.Statement\n ? (Array.isArray(doc.Statement) ? doc.Statement : [doc.Statement])\n : [];\n rawStatements.forEach(function(stmt, idx) {\n stmt = stmt || {};\n if (stmt.Effect !== 'Allow' && stmt.Effect !== 'Deny') {\n // Defaulting a missing/malformed Effect to \"Allow\" would\n // silently turn e.g. a typo'd \"deny\" into a permissive\n // statement. Reject instead of guessing.\n throw new Error('Statement ' + (idx + 1) + ': Effect must be exactly \"Allow\" or \"Deny\" (got ' +\n JSON.stringify(stmt.Effect === undefined ? null : stmt.Effect) + ')');\n }\n const hasResource = Object.prototype.hasOwnProperty.call(stmt, 'Resource');\n const hasNotResource = Object.prototype.hasOwnProperty.call(stmt, 'NotResource');\n if (hasResource && hasNotResource) {\n // The two are mutually exclusive; a document with both isn't\n // representable by the mode dropdown, so ask the user to fix\n // it in the JSON tab rather than silently picking one.\n throw new Error('Statement ' + (idx + 1) + ': cannot specify both Resource and NotResource');\n }\n const resourceMode = hasNotResource ? 'NotResource' : 'Resource';\n\n const hasPrincipal = Object.prototype.hasOwnProperty.call(stmt, 'Principal');\n const hasNotPrincipal = Object.prototype.hasOwnProperty.call(stmt, 'NotPrincipal');\n if (hasPrincipal && hasNotPrincipal) {\n throw new Error('Statement ' + (idx + 1) + ': cannot specify both Principal and NotPrincipal');\n }\n let principalMode = 'Principal';\n let principalValues = [];\n let principalManaged = false;\n let hasComplexPrincipal = false;\n if (hasPrincipal || hasNotPrincipal) {\n const principalKey = hasNotPrincipal ? 'NotPrincipal' : 'Principal';\n const parsedValues = parseSimpleAwsPrincipal(stmt[principalKey]);\n if (parsedValues) {\n principalMode = principalKey;\n principalValues = parsedValues;\n principalManaged = true;\n } else {\n // Bare string/array, a type other than AWS, or multiple\n // types at once - this v1 editor only models a single\n // {\"AWS\": ...} form. Leave it in extras rather than\n // guessing or discarding it.\n hasComplexPrincipal = true;\n }\n }\n\n const extras = {};\n Object.keys(stmt).forEach(function(key) {\n if (POLICY_STATEMENT_KNOWN_KEYS.indexOf(key) !== -1) return;\n if (principalManaged && (key === 'Principal' || key === 'NotPrincipal')) return;\n extras[key] = stmt[key];\n });\n state.statements.push({\n sid: String(stmt.Sid || ''),\n effect: stmt.Effect,\n actions: normalizeToStringArray(stmt.Action),\n resourceMode: resourceMode,\n resources: normalizeToStringArray(hasNotResource ? stmt.NotResource : stmt.Resource),\n principalMode: principalMode,\n principalValues: principalValues,\n hasComplexPrincipal: hasComplexPrincipal,\n extras: Object.keys(extras).length ? JSON.stringify(extras, null, 2) : ''\n });\n });\n return state;\n }\n\n // Returns the flattened list of values if `value` is a policy Principal /\n // NotPrincipal expressed as one of the two forms this editor's simple\n // text field models: the bare wildcard \"*\" (standard AWS shorthand for\n // \"everyone\"), or a single-key {\"AWS\": \"...\"} / {\"AWS\": [\"...\", ...]}\n // object. Returns null for anything else (any other bare string/array, a\n // different type key, or multiple type keys at once), which the caller\n // then leaves untouched in \"extras\".\n function parseSimpleAwsPrincipal(value) {\n if (value === '*') return ['*'];\n if (!value || typeof value !== 'object' || Array.isArray(value)) return null;\n const keys = Object.keys(value);\n if (keys.length !== 1 || keys[0] !== 'AWS') return null;\n return normalizeToStringArray(value.AWS);\n }\n\n // Converts editor state back into a policy document. Structured fields\n // (Sid/Effect/Action/Resource-or-NotResource) always take precedence over\n // whatever is in \"extras\" in case of a conflicting key.\n //\n // Throws if a statement's \"advanced fields\" box holds malformed or\n // non-object JSON, instead of silently dropping it: those fields can\n // carry Principal/NotPrincipal/Condition, so silently continuing with an\n // empty object would change the policy's authorization behavior without\n // the user noticing.\n function policyEditorStateToDoc(state) {\n // Unmanaged top-level keys first, so Version/Statement below always win.\n const doc = Object.assign({}, state.otherFields || {});\n doc.Version = state.version || '2012-10-17';\n doc.Statement = [];\n (state.statements || []).forEach(function(s, idx) {\n let stmt = {};\n if (s.extras && s.extras.trim()) {\n let parsed;\n try {\n parsed = JSON.parse(s.extras);\n } catch (e) {\n throw new Error('Statement ' + (idx + 1) + ': advanced fields contain invalid JSON (' + e.message + ')');\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('Statement ' + (idx + 1) + ': advanced fields must be a JSON object');\n }\n stmt = parsed;\n }\n if (s.sid) {\n stmt.Sid = s.sid;\n } else {\n delete stmt.Sid;\n }\n stmt.Effect = s.effect === 'Deny' ? 'Deny' : 'Allow';\n const actions = (s.actions || []).map(function(a) { return (a || '').trim(); }).filter(Boolean);\n if (actions.length) {\n stmt.Action = actions.length === 1 ? actions[0] : actions;\n } else {\n delete stmt.Action;\n }\n const resources = (s.resources || []).map(function(r) { return (r || '').trim(); }).filter(Boolean);\n if (resources.length) {\n // Resource and NotResource are mutually exclusive; only the\n // key matching the selected mode is ever written.\n if (s.resourceMode === 'NotResource') {\n stmt.NotResource = resources.length === 1 ? resources[0] : resources;\n delete stmt.Resource;\n } else {\n stmt.Resource = resources.length === 1 ? resources[0] : resources;\n delete stmt.NotResource;\n }\n } else {\n delete stmt.Resource;\n delete stmt.NotResource;\n }\n const principalValues = (s.principalValues || []).map(function(p) { return (p || '').trim(); }).filter(Boolean);\n if (principalValues.length) {\n // Same exclusivity rule as Resource/NotResource. Structured\n // values always win over whatever \"extras\" held for these\n // keys. A lone \"*\" is written as the bare wildcard (standard\n // AWS shorthand for \"everyone\"); anything else is wrapped in\n // the standard {\"AWS\": ...} form (v1 only models AWS\n // principals).\n delete stmt.Principal;\n delete stmt.NotPrincipal;\n const wrappedPrincipal = (principalValues.length === 1 && principalValues[0] === '*')\n ? '*'\n : { AWS: principalValues.length === 1 ? principalValues[0] : principalValues };\n if (s.principalMode === 'NotPrincipal') {\n stmt.NotPrincipal = wrappedPrincipal;\n } else {\n stmt.Principal = wrappedPrincipal;\n }\n }\n // If principalValues is empty, leave stmt.Principal/NotPrincipal\n // untouched: it may hold a complex form preserved verbatim from\n // \"extras\" (see parseSimpleAwsPrincipal) that the user never\n // touched via this field, and clearing it here would silently\n // discard it.\n doc.Statement.push(stmt);\n });\n return doc;\n }\n\n // Renders the structured editor for the given modal (\"create\"/\"edit\")\n // from policyEditors[which] into its container.\n function renderPolicyEditor(which) {\n const container = document.getElementById(policyEditorBodyId(which));\n if (!container) return;\n const state = policyEditors[which];\n\n if (state.unparsed) {\n container.innerHTML = '<p class=\"text-muted\">This policy uses a form the structured editor cannot show. Edit it on the JSON tab.</p>';\n return;\n }\n\n if (state.statements.length === 0) {\n container.innerHTML = '<p class=\"text-muted\">No statements yet. Click \"Add statement\" to create one.</p>';\n return;\n }\n\n let html = '';\n state.statements.forEach(function(stmt, idx) {\n const actionRows = stmt.actions.map(function(action, actionIdx) {\n return policyListRowHtml(which, idx, 'action', actionIdx, action);\n }).join('');\n const resourceRows = stmt.resources.map(function(resource, resourceIdx) {\n return policyListRowHtml(which, idx, 'resource', resourceIdx, resource);\n }).join('');\n const principalRows = stmt.principalValues.map(function(principal, principalIdx) {\n return policyListRowHtml(which, idx, 'principal', principalIdx, principal);\n }).join('');\n\n html +=\n '<div class=\"card mb-3\" data-statement-index=\"' + idx + '\">' +\n '<div class=\"card-body\">' +\n '<div class=\"d-flex justify-content-between align-items-start mb-2\">' +\n '<h6 class=\"card-title mb-0\">Statement ' + (idx + 1) + '</h6>' +\n '<button type=\"button\" class=\"btn btn-sm btn-outline-danger policy-remove-statement-btn\" data-which=\"' + which + '\" data-index=\"' + idx + '\"><i class=\"fas fa-trash\"></i></button>' +\n '</div>' +\n '<div class=\"row mb-2\">' +\n '<div class=\"col-md-6\">' +\n '<label class=\"form-label\">Sid (optional)</label>' +\n '<input type=\"text\" class=\"form-control form-control-sm policy-stmt-sid\" data-which=\"' + which + '\" data-index=\"' + idx + '\" value=\"' + escapeHtml(stmt.sid) + '\">' +\n '</div>' +\n '<div class=\"col-md-6\">' +\n '<label class=\"form-label d-block\">Effect</label>' +\n '<div class=\"btn-group\" role=\"group\">' +\n '<input type=\"radio\" class=\"btn-check policy-stmt-effect\" name=\"policyEffect-' + which + '-' + idx + '\" id=\"policyEffectAllow-' + which + '-' + idx + '\" data-which=\"' + which + '\" data-index=\"' + idx + '\" value=\"Allow\"' + (stmt.effect === 'Allow' ? ' checked' : '') + '>' +\n '<label class=\"btn btn-outline-success btn-sm\" for=\"policyEffectAllow-' + which + '-' + idx + '\">Allow</label>' +\n '<input type=\"radio\" class=\"btn-check policy-stmt-effect\" name=\"policyEffect-' + which + '-' + idx + '\" id=\"policyEffectDeny-' + which + '-' + idx + '\" data-which=\"' + which + '\" data-index=\"' + idx + '\" value=\"Deny\"' + (stmt.effect === 'Deny' ? ' checked' : '') + '>' +\n '<label class=\"btn btn-outline-danger btn-sm\" for=\"policyEffectDeny-' + which + '-' + idx + '\">Deny</label>' +\n '</div>' +\n '</div>' +\n '</div>' +\n '<fieldset class=\"policy-stmt-fieldset\">' +\n '<legend class=\"policy-stmt-legend border rounded\">Actions</legend>' +\n '<div class=\"policy-action-rows\" data-which=\"' + which + '\" data-index=\"' + idx + '\">' + actionRows + '</div>' +\n '<button type=\"button\" class=\"btn btn-sm btn-outline-secondary policy-add-list-item-btn\" data-which=\"' + which + '\" data-index=\"' + idx + '\" data-field=\"action\"><i class=\"fas fa-plus me-1\"></i>Add action</button>' +\n '</fieldset>' +\n '<fieldset class=\"policy-stmt-fieldset\">' +\n '<legend class=\"policy-stmt-legend\">' +\n '<select class=\"form-select form-select-sm d-inline-block w-auto policy-stmt-resource-mode\" data-which=\"' + which + '\" data-index=\"' + idx + '\">' +\n '<option value=\"Resource\"' + (stmt.resourceMode !== 'NotResource' ? ' selected' : '') + '>Resource</option>' +\n '<option value=\"NotResource\"' + (stmt.resourceMode === 'NotResource' ? ' selected' : '') + '>NotResource</option>' +\n '</select>' +\n '</legend>' +\n (stmt.resourceMode === 'NotResource' ? '<div class=\"form-text mt-0 mb-1\">The statement applies to every resource except the ones listed.</div>' : '') +\n '<div class=\"policy-resource-rows\" data-which=\"' + which + '\" data-index=\"' + idx + '\">' + resourceRows + '</div>' +\n '<button type=\"button\" class=\"btn btn-sm btn-outline-secondary policy-add-list-item-btn\" data-which=\"' + which + '\" data-index=\"' + idx + '\" data-field=\"resource\"><i class=\"fas fa-plus me-1\"></i>Add resource</button>' +\n '</fieldset>' +\n '<fieldset class=\"policy-stmt-fieldset\">' +\n '<legend class=\"policy-stmt-legend\">' +\n '<select class=\"form-select form-select-sm d-inline-block w-auto policy-stmt-principal-mode\" data-which=\"' + which + '\" data-index=\"' + idx + '\">' +\n '<option value=\"Principal\"' + (stmt.principalMode !== 'NotPrincipal' ? ' selected' : '') + '>Principal</option>' +\n '<option value=\"NotPrincipal\"' + (stmt.principalMode === 'NotPrincipal' ? ' selected' : '') + '>NotPrincipal</option>' +\n '</select>' +\n '</legend>' +\n '<div class=\"form-text mt-0 mb-1\">Principal / NotPrincipal (AWS account/user ARN, or \"*\" for everyone). Only the AWS type and \"*\" are supported here; other forms stay editable via Advanced fields.</div>' +\n (stmt.hasComplexPrincipal ? '<div class=\"form-text text-warning mt-0 mb-1\"><i class=\"fas fa-triangle-exclamation me-1\"></i>This statement\\'s Principal/NotPrincipal uses a form not supported by this field — see Advanced fields below.</div>' : '') +\n '<div class=\"policy-principal-rows\" data-which=\"' + which + '\" data-index=\"' + idx + '\">' + principalRows + '</div>' +\n '<button type=\"button\" class=\"btn btn-sm btn-outline-secondary policy-add-list-item-btn\" data-which=\"' + which + '\" data-index=\"' + idx + '\" data-field=\"principal\"><i class=\"fas fa-plus me-1\"></i>Add principal</button>' +\n '</fieldset>' +\n '<details class=\"mt-3\"' + (stmt.extras ? ' open' : '') + '>' +\n '<summary class=\"text-muted\">Advanced fields (Principal, NotPrincipal, Condition, raw JSON)</summary>' +\n '<textarea class=\"form-control form-control-sm mt-2 policy-stmt-extras\" data-which=\"' + which + '\" data-index=\"' + idx + '\" rows=\"4\" placeholder=\"{}\">' + escapeHtml(stmt.extras) + '</textarea>' +\n '</details>' +\n '</div>' +\n '</div>';\n });\n container.innerHTML = html;\n }\n\n function policyListRowHtml(which, stmtIdx, field, itemIdx, value) {\n let listAttr = '';\n if (field === 'action') listAttr = ' list=\"policyActionSuggestions\"';\n else if (field === 'resource') listAttr = ' list=\"policyResourceSuggestions\"';\n else if (field === 'principal') listAttr = ' list=\"policyPrincipalSuggestions\"';\n return '<div class=\"input-group input-group-sm mb-1\">' +\n '<input type=\"text\" class=\"form-control policy-list-item\" ' + listAttr + ' data-which=\"' + which + '\" data-index=\"' + stmtIdx + '\" data-field=\"' + field + '\" data-item-index=\"' + itemIdx + '\" value=\"' + escapeHtml(value) + '\">' +\n '<button type=\"button\" class=\"btn btn-outline-danger policy-remove-list-item-btn\" data-which=\"' + which + '\" data-index=\"' + stmtIdx + '\" data-field=\"' + field + '\" data-item-index=\"' + itemIdx + '\"><i class=\"fas fa-times\"></i></button>' +\n '</div>';\n }\n\n // Reads whatever is currently displayed in the editor tab's DOM back into\n // policyEditors[which], so nothing typed is lost before a save/tab-switch/serialize.\n function commitPolicyEditorForm(which) {\n const state = policyEditors[which];\n if (!state) return;\n\n document.querySelectorAll('.policy-stmt-sid[data-which=\"' + which + '\"]').forEach(function(el) {\n const idx = parseInt(el.getAttribute('data-index'), 10);\n if (state.statements[idx]) state.statements[idx].sid = el.value;\n });\n document.querySelectorAll('.policy-stmt-effect[data-which=\"' + which + '\"]:checked').forEach(function(el) {\n const idx = parseInt(el.getAttribute('data-index'), 10);\n if (state.statements[idx]) state.statements[idx].effect = el.value;\n });\n document.querySelectorAll('.policy-stmt-extras[data-which=\"' + which + '\"]').forEach(function(el) {\n const idx = parseInt(el.getAttribute('data-index'), 10);\n if (state.statements[idx]) state.statements[idx].extras = el.value;\n });\n document.querySelectorAll('.policy-stmt-resource-mode[data-which=\"' + which + '\"]').forEach(function(el) {\n const idx = parseInt(el.getAttribute('data-index'), 10);\n if (state.statements[idx]) state.statements[idx].resourceMode = el.value;\n });\n document.querySelectorAll('.policy-stmt-principal-mode[data-which=\"' + which + '\"]').forEach(function(el) {\n const idx = parseInt(el.getAttribute('data-index'), 10);\n if (state.statements[idx]) state.statements[idx].principalMode = el.value;\n });\n document.querySelectorAll('.policy-list-item[data-which=\"' + which + '\"]').forEach(function(el) {\n const idx = parseInt(el.getAttribute('data-index'), 10);\n const itemIdx = parseInt(el.getAttribute('data-item-index'), 10);\n const field = POLICY_LIST_FIELD_TO_STATE_KEY[el.getAttribute('data-field')] || 'resources';\n if (state.statements[idx] && state.statements[idx][field]) {\n state.statements[idx][field][itemIdx] = el.value;\n }\n });\n }\n\n // Serializes policyEditors[which] into the JSON textarea. Call before\n // switching to the JSON tab or before submitting, so the textarea always\n // reflects the editor's current contents.\n function commitPolicyEditorToTextarea(which) {\n commitPolicyEditorForm(which);\n const doc = policyEditorStateToDoc(policyEditors[which]);\n document.getElementById(policyTextareaId(which)).value = JSON.stringify(doc, null, 2);\n }\n\n // Parses the JSON textarea into policyEditors[which] and re-renders the\n // editor. Returns false (and shows an alert) if the JSON is invalid or a\n // statement's Effect isn't exactly \"Allow\"/\"Deny\", leaving the JSON tab\n // as the active one so the user can fix it.\n function commitPolicyTextareaToEditor(which) {\n const text = document.getElementById(policyTextareaId(which)).value;\n if (!text || !text.trim()) {\n policyEditors[which] = { version: '2012-10-17', statements: [], otherFields: {} };\n renderPolicyEditor(which);\n return true;\n }\n let doc;\n try {\n doc = JSON.parse(text);\n } catch (e) {\n showAlert('Invalid JSON in policy document: ' + e.message, 'error');\n return false;\n }\n let newState;\n try {\n newState = policyDocToEditorState(doc);\n } catch (e) {\n showAlert(e.message, 'error');\n return false;\n }\n policyEditors[which] = newState;\n renderPolicyEditor(which);\n return true;\n }\n\n function addPolicyStatement(which) {\n if (policyEditors[which].unparsed) {\n showAlert(POLICY_JSON_TAB_ONLY_MESSAGE, 'error');\n return;\n }\n commitPolicyEditorForm(which);\n policyEditors[which].statements.push({\n sid: '', effect: 'Allow', actions: [],\n resourceMode: 'Resource', resources: [],\n principalMode: 'Principal', principalValues: [], hasComplexPrincipal: false,\n extras: ''\n });\n renderPolicyEditor(which);\n }\n\n // True while the JSON tab (rather than the Editor tab) is the one\n // currently shown for `which`.\n function isPolicyJsonTabActive(which) {\n const jsonTabBtn = document.getElementById(which + 'PolicyJsonTabBtn');\n return !!(jsonTabBtn && jsonTabBtn.classList.contains('active'));\n }\n\n // Commits whichever tab is currently visible into the other side, so a\n // save/validate action always uses what the user is actually looking at\n // instead of silently overwriting it with stale state from the tab\n // they're not on. Returns false (after alerting the user) if that isn't\n // possible - e.g. invalid JSON on either side - so the caller can abort.\n function commitPolicyActiveTab(which) {\n if (isPolicyJsonTabActive(which)) {\n // The JSON tab is the source of truth right now; parse it back\n // into the structured editor to keep both in sync, but leave the\n // textarea's own text untouched.\n return commitPolicyTextareaToEditor(which);\n }\n if (policyEditors[which] && policyEditors[which].unparsed) {\n // The editor never held this document, so serializing it would\n // write an empty policy over whatever is in the JSON tab.\n showAlert(POLICY_JSON_TAB_ONLY_MESSAGE, 'error');\n return false;\n }\n try {\n commitPolicyEditorToTextarea(which);\n return true;\n } catch (e) {\n showAlert(e.message, 'error');\n return false;\n }\n }\n\n // The admin API's policy document carries only Version and Statement, so\n // any other top-level key (e.g. Id) is discarded server-side on save even\n // though the editor round-trips it between tabs. Warn before that happens\n // rather than letting the field vanish silently. Returns false if the\n // user cancels.\n function confirmPolicyFieldDiscard(which) {\n const otherFields = Object.keys((policyEditors[which] || {}).otherFields || {});\n if (otherFields.length === 0) return true;\n return confirm(\n 'The following top-level field(s) are not supported and will be dropped when this policy is saved: ' +\n otherFields.join(', ') + '.\\n\\nSave anyway?');\n }\n\n function setupPolicyEditor(which) {\n document.getElementById(which + 'PolicyAddStatementBtn').addEventListener('click', function() {\n addPolicyStatement(which);\n });\n\n const editorTabBtn = document.getElementById(which + 'PolicyEditorTabBtn');\n const jsonTabBtn = document.getElementById(which + 'PolicyJsonTabBtn');\n\n jsonTabBtn.addEventListener('show.bs.tab', function(event) {\n if (policyEditors[which].unparsed) {\n // The editor never held this document; serializing its empty\n // placeholder state would overwrite the textarea we are about\n // to show, which is the only copy of it.\n return;\n }\n try {\n commitPolicyEditorToTextarea(which);\n } catch (e) {\n showAlert(e.message, 'error');\n event.preventDefault();\n }\n });\n editorTabBtn.addEventListener('show.bs.tab', function(event) {\n if (!commitPolicyTextareaToEditor(which)) {\n event.preventDefault();\n }\n });\n\n const body = document.getElementById(policyEditorBodyId(which));\n body.addEventListener('change', function(event) {\n if (event.target.classList.contains('policy-stmt-resource-mode')) {\n // Redraw so the NotResource hint follows the selected mode.\n commitPolicyEditorForm(which);\n renderPolicyEditor(which);\n }\n });\n body.addEventListener('click', function(event) {\n const removeStmtBtn = event.target.closest('.policy-remove-statement-btn');\n if (removeStmtBtn) {\n commitPolicyEditorForm(which);\n const idx = parseInt(removeStmtBtn.getAttribute('data-index'), 10);\n policyEditors[which].statements.splice(idx, 1);\n renderPolicyEditor(which);\n return;\n }\n const addItemBtn = event.target.closest('.policy-add-list-item-btn');\n if (addItemBtn) {\n commitPolicyEditorForm(which);\n const idx = parseInt(addItemBtn.getAttribute('data-index'), 10);\n const field = POLICY_LIST_FIELD_TO_STATE_KEY[addItemBtn.getAttribute('data-field')] || 'resources';\n policyEditors[which].statements[idx][field].push('');\n renderPolicyEditor(which);\n return;\n }\n const removeItemBtn = event.target.closest('.policy-remove-list-item-btn');\n if (removeItemBtn) {\n commitPolicyEditorForm(which);\n const idx = parseInt(removeItemBtn.getAttribute('data-index'), 10);\n const itemIdx = parseInt(removeItemBtn.getAttribute('data-item-index'), 10);\n const field = POLICY_LIST_FIELD_TO_STATE_KEY[removeItemBtn.getAttribute('data-field')] || 'resources';\n policyEditors[which].statements[idx][field].splice(itemIdx, 1);\n renderPolicyEditor(which);\n }\n });\n\n // Populate the shared Resource datalist as the user types/focuses a\n // Resource field. Bootstrap's datalist filtering then narrows down\n // whatever set of options was last loaded for the current path stage.\n body.addEventListener('input', function(event) {\n const target = event.target;\n if (target.classList.contains('policy-list-item') && target.getAttribute('data-field') === 'resource') {\n updatePolicyResourceSuggestions(target);\n }\n });\n body.addEventListener('focusin', function(event) {\n const target = event.target;\n if (target.classList.contains('policy-list-item') && target.getAttribute('data-field') === 'resource') {\n updatePolicyResourceSuggestions(target);\n }\n });\n\n // Same idea for the shared Principal datalist: a flat, one-time\n // fetch (see loadPolicyPrincipalSuggestions), no per-segment logic\n // needed since users/roles aren't hierarchical like bucket paths.\n body.addEventListener('input', function(event) {\n const target = event.target;\n if (target.classList.contains('policy-list-item') && target.getAttribute('data-field') === 'principal') {\n updatePolicyPrincipalSuggestions();\n }\n });\n body.addEventListener('focusin', function(event) {\n const target = event.target;\n if (target.classList.contains('policy-list-item') && target.getAttribute('data-field') === 'principal') {\n updatePolicyPrincipalSuggestions();\n }\n });\n }\n\n // ------------------------------------------------------------------\n // Progressive Resource ARN autocomplete: suggests bucket names first\n // (arn:aws:s3:::bucket), then once a bucket + \"/\" is typed, suggests\n // arn:aws:s3:::bucket/* plus the direct subfolders one path segment at a\n // time (fetched from the server on demand, one directory level per\n // request, and cached per directory for the life of the page).\n // ------------------------------------------------------------------\n\n const POLICY_RESOURCE_ARN_PREFIX = 'arn:aws:s3:::';\n let policyBucketArnsPromise = null;\n const policyFolderListCache = new Map();\n\n function loadPolicyBucketArns() {\n if (!policyBucketArnsPromise) {\n policyBucketArnsPromise = fetch(basePath('/api/s3/buckets'))\n .then(function(r) { return r.ok ? r.json() : { buckets: [] }; })\n .then(function(data) {\n // Offer both the bucket itself and \"every object in it\",\n // since the latter is what most Resource entries actually need.\n return (data.buckets || []).reduce(function(acc, b) {\n const arn = POLICY_RESOURCE_ARN_PREFIX + b.name;\n acc.push(arn, arn + '/*');\n return acc;\n }, []);\n })\n .catch(function() { return []; });\n }\n return policyBucketArnsPromise;\n }\n\n function loadPolicyFolderNames(dirPath, prefix) {\n // Send the segment still being typed as a prefix so the filer does the\n // filtering: without it the server pages through every entry in the\n // directory, which on a bucket of flat object keys is the whole bucket.\n const key = dirPath + '\\n' + prefix;\n if (!policyFolderListCache.has(key)) {\n policyFolderListCache.set(key, fetch(basePath('/api/files/list-folders?path=' + encodeURIComponent(dirPath) +\n '&prefix=' + encodeURIComponent(prefix)))\n .then(function(r) {\n if (!r.ok) throw new Error('list-folders request failed with status ' + r.status);\n return r.json();\n })\n .then(function(data) { return data.folders || []; })\n .catch(function() {\n // Don't let a transient failure permanently poison the\n // cache for this directory; let the next call retry.\n policyFolderListCache.delete(key);\n return [];\n }));\n }\n return policyFolderListCache.get(key);\n }\n\n // Figures out what stage of the ARN the user is currently typing:\n // still the bucket name (\"bucket\"), or a folder path segment after the\n // bucket (\"folder\", with dirPath being the filer directory to list and\n // arnPrefix being the ARN text to append suggestions onto).\n function policyResourcePathState(value) {\n value = value || '';\n if (value.indexOf(POLICY_RESOURCE_ARN_PREFIX) !== 0) {\n return { stage: 'bucket' };\n }\n const rest = value.slice(POLICY_RESOURCE_ARN_PREFIX.length);\n const segments = rest.split('/');\n if (segments.length === 1) {\n return { stage: 'bucket' };\n }\n const bucket = segments[0];\n const pathSegments = segments.slice(1, segments.length - 1);\n const suffix = pathSegments.length ? '/' + pathSegments.join('/') : '';\n return {\n stage: 'folder',\n dirPath: '/buckets/' + bucket + suffix,\n // The trailing, still-incomplete segment. The datalist narrows on\n // it too, but sending it keeps the server's listing bounded.\n prefix: segments[segments.length - 1],\n arnPrefix: POLICY_RESOURCE_ARN_PREFIX + bucket + suffix\n };\n }\n\n function renderPolicyDatalistOptions(datalist, values) {\n datalist.innerHTML = values.map(function(v) {\n return '<option value=\"' + escapeHtml(v) + '\"></option>';\n }).join('');\n }\n\n function updatePolicyResourceSuggestions(inputEl) {\n const datalist = document.getElementById('policyResourceSuggestions');\n if (!datalist) return;\n const state = policyResourcePathState(inputEl.value);\n\n if (state.stage === 'bucket') {\n loadPolicyBucketArns().then(function(arns) {\n renderPolicyDatalistOptions(datalist, arns);\n });\n return;\n }\n\n loadPolicyFolderNames(state.dirPath, state.prefix).then(function(folders) {\n const options = [state.arnPrefix + '/*'];\n folders.forEach(function(name) {\n options.push(state.arnPrefix + '/' + name);\n });\n renderPolicyDatalistOptions(datalist, options);\n });\n }\n\n // ------------------------------------------------------------------\n // Principal autocomplete: a flat list of existing users and IAM roles,\n // fetched once from /api/principals and cached for the life of the page\n // (unlike Resource ARNs, users/roles have no hierarchy to drill into).\n // ------------------------------------------------------------------\n\n let policyPrincipalSuggestionsPromise = null;\n\n function loadPolicyPrincipalSuggestions() {\n if (!policyPrincipalSuggestionsPromise) {\n policyPrincipalSuggestionsPromise = fetch(basePath('/api/principals'))\n .then(function(r) { return r.ok ? r.json() : { principals: [] }; })\n .then(function(data) { return ['*'].concat(data.principals || []); })\n .catch(function() { return ['*']; });\n }\n return policyPrincipalSuggestionsPromise;\n }\n\n function updatePolicyPrincipalSuggestions() {\n const datalist = document.getElementById('policyPrincipalSuggestions');\n if (!datalist) return;\n loadPolicyPrincipalSuggestions().then(function(principals) {\n renderPolicyDatalistOptions(datalist, principals);\n });\n }\n\n // Fills the structured editor (and the JSON tab) with a sample policy,\n // regardless of which tab is currently active.\n const POLICY_SAMPLE_DOCUMENT = {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::my-bucket/*\"\n ]\n }\n ]\n };\n\n function insertSamplePolicy(which) {\n policyEditors[which] = policyDocToEditorState(POLICY_SAMPLE_DOCUMENT);\n renderPolicyEditor(which);\n document.getElementById(policyTextareaId(which)).value = JSON.stringify(POLICY_SAMPLE_DOCUMENT, null, 2);\n }\n\n // Event listeners for policy actions\n document.addEventListener('DOMContentLoaded', function() {\n setupPolicyEditor('create');\n setupPolicyEditor('edit');\n\n // View policy buttons\n document.querySelectorAll('.view-policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const policyName = this.getAttribute('data-policy-name');\n viewPolicy(policyName);\n });\n });\n\n // Edit policy buttons\n document.querySelectorAll('.edit-policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const policyName = this.getAttribute('data-policy-name');\n editPolicy(policyName);\n });\n });\n\n // Delete policy buttons\n document.querySelectorAll('.delete-policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const policyName = this.getAttribute('data-policy-name');\n deletePolicy(policyName);\n });\n });\n\n // Edit from view button\n document.getElementById('editFromViewBtn').addEventListener('click', function() {\n if (currentPolicy) {\n const viewModal = bootstrap.Modal.getInstance(document.getElementById('viewPolicyModal'));\n if (viewModal) viewModal.hide();\n editPolicy(currentPolicy.name);\n }\n });\n\n // Reset the create modal's editor each time it's opened, so leftover\n // state from a previous (possibly cancelled) create doesn't leak in.\n document.getElementById('createPolicyModal').addEventListener('show.bs.modal', function() {\n document.getElementById('createPolicyForm').reset();\n policyEditors.create = { version: '2012-10-17', statements: [], otherFields: {} };\n renderPolicyEditor('create');\n const editorTab = bootstrap.Tab.getOrCreateInstance(document.getElementById('createPolicyEditorTabBtn'));\n editorTab.show();\n });\n });\n\n function createPolicy() {\n if (!commitPolicyActiveTab('create')) return;\n if (!confirmPolicyFieldDiscard('create')) return;\n\n const policyName = document.getElementById('policyName').value;\n const policyDocumentText = document.getElementById('policyDocument').value;\n\n if (!policyName || !policyDocumentText) {\n showAlert('Please fill in all required fields', 'warning');\n return;\n }\n\n let policyDocument;\n try {\n policyDocument = JSON.parse(policyDocumentText);\n } catch (e) {\n showAlert('Invalid JSON in policy document: ' + e.message, 'error');\n return;\n }\n\n const requestData = {\n name: policyName,\n document: policyDocument\n };\n\n validatePolicyJSON(policyDocumentText, true).then(valid => {\n if (!valid) return;\n\n fetch(basePath('/api/object-store/policies'), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestData)\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Policy created successfully!', 'success');\n const modal = bootstrap.Modal.getInstance(document.getElementById('createPolicyModal'));\n if (modal) modal.hide();\n location.reload(); // Refresh the page to show the new policy\n } else {\n showAlert('Error creating policy: ' + (data.error || 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error creating policy: ' + error.message, 'error');\n });\n });\n }\n\n function viewPolicy(policyName) {\n // Show the modal first\n const modal = new bootstrap.Modal(document.getElementById('viewPolicyModal'));\n modal.show();\n\n // Reset content to loading state\n document.getElementById('viewPolicyContent').innerHTML = `\n <div class=\"text-center\">\n <div class=\"spinner-border\" role=\"status\">\n <span class=\"visually-hidden\">Loading...</span>\n </div>\n <p class=\"mt-2\">Loading policy...</p>\n </div>\n `;\n\n // Fetch policy data\n fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)))\n .then(response => {\n if (!response.ok) {\n throw new Error('Policy not found');\n }\n return response.json();\n })\n .then(policy => {\n currentPolicy = policy;\n displayPolicyDetails(policy);\n })\n .catch(error => {\n console.error('Error:', error);\n document.getElementById('viewPolicyContent').innerHTML = `\n <div class=\"alert alert-danger\" role=\"alert\">\n <i class=\"fas fa-exclamation-triangle me-2\"></i>\n Error loading policy: ${error.message}\n </div>\n `;\n });\n }\n\n function displayPolicyDetails(policy) {\n const content = document.getElementById('viewPolicyContent');\n\n // Escapes a policy value for display, whether it's carried as a\n // single value or a list, and whatever type it turns out to be.\n function escapedJoin(list) {\n if (list === undefined || list === null) return '';\n return (Array.isArray(list) ? list : [list]).map(function(v) { return escapeHtml(String(v)); }).join(', ');\n }\n\n // Summarizes a Principal/NotPrincipal value for read-only display,\n // regardless of shape (bare string/array, or a {\"Type\": ...} object -\n // possibly with several type keys), since the View modal must stay\n // correct even for forms the structured editor doesn't model.\n function principalSummary(value) {\n if (value === undefined || value === null) return '';\n if (Array.isArray(value)) return escapedJoin(value);\n if (typeof value === 'object') {\n return Object.keys(value).map(function(key) {\n const v = value[key];\n return escapeHtml(key) + ': ' + escapedJoin(v);\n }).join('; ');\n }\n return escapeHtml(String(value));\n }\n\n let statementsHtml = '';\n if (policy.document && policy.document.Statement) {\n statementsHtml = policy.document.Statement.map((stmt, index) => `\n <div class=\"card mb-2\">\n <div class=\"card-header py-2\">\n <h6 class=\"mb-0\">Statement ${index + 1}${stmt.Sid ? ' — ' + escapeHtml(stmt.Sid) : ''}</h6>\n </div>\n <div class=\"card-body py-2\">\n <div class=\"row\">\n <div class=\"col-md-6\">\n <strong>Effect:</strong>\n <span class=\"badge ${stmt.Effect === 'Allow' ? 'bg-success' : 'bg-danger'}\">${escapedJoin(stmt.Effect)}</span>\n </div>\n <div class=\"col-md-6\">\n <strong>Actions:</strong> ${escapedJoin(stmt.Action)}\n </div>\n </div>\n <div class=\"row mt-2\">\n <div class=\"col-12\">\n ${stmt.NotResource\n ? '<strong>NotResource (excluded):</strong> ' + escapedJoin(stmt.NotResource)\n : '<strong>Resource:</strong> ' + escapedJoin(stmt.Resource)}\n </div>\n </div>\n ${(stmt.Principal || stmt.NotPrincipal)\n ? '<div class=\"row mt-2\"><div class=\"col-12\">' +\n (stmt.NotPrincipal\n ? '<strong>NotPrincipal (excluded):</strong> ' + principalSummary(stmt.NotPrincipal)\n : '<strong>Principal:</strong> ' + principalSummary(stmt.Principal)) +\n '</div></div>'\n : ''}\n </div>\n </div>\n `).join('');\n }\n\n content.innerHTML = `\n <div class=\"row mb-3\">\n <div class=\"col-md-6\">\n <strong>Policy Name:</strong> ${escapedJoin(policy.name || 'Unknown')}\n </div>\n <div class=\"col-md-6\">\n <strong>Version:</strong> <span class=\"badge bg-info\">${escapedJoin(policy.document?.Version || 'Unknown')}</span>\n </div>\n </div>\n\n <div class=\"mb-3\">\n <strong>Statements:</strong>\n <div class=\"mt-2\">\n ${statementsHtml || '<p class=\"text-muted\">No statements found</p>'}\n </div>\n </div>\n\n <div class=\"mb-3\">\n <strong>Raw Policy Document:</strong>\n <pre class=\"bg-light p-3 border rounded mt-2\"><code>${escapeHtml(JSON.stringify(policy.document, null, 2))}</code></pre>\n </div>\n `;\n }\n\n function editPolicy(policyName) {\n // Show the modal first\n const modal = new bootstrap.Modal(document.getElementById('editPolicyModal'));\n modal.show();\n\n // Set policy name\n document.getElementById('editPolicyName').value = policyName;\n document.getElementById('editPolicyDocument').value = 'Loading...';\n policyEditors.edit = { version: '2012-10-17', statements: [], otherFields: {} };\n renderPolicyEditor('edit');\n\n // Fetch policy data\n fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)))\n .then(response => {\n if (!response.ok) {\n throw new Error('Policy not found');\n }\n return response.json();\n })\n .then(policy => {\n currentPolicy = policy;\n document.getElementById('editPolicyDocument').value = JSON.stringify(policy.document, null, 2);\n let state;\n try {\n state = policyDocToEditorState(policy.document);\n } catch (e) {\n // Valid JSON the structured editor can't model. The JSON tab\n // exists for exactly this, so hand the document over to it\n // rather than closing the modal on the only view of it.\n policyEditors.edit = { version: '2012-10-17', statements: [], otherFields: {}, unparsed: true };\n renderPolicyEditor('edit');\n showAlert(e.message + '. ' + POLICY_JSON_TAB_ONLY_MESSAGE, 'error');\n bootstrap.Tab.getOrCreateInstance(document.getElementById('editPolicyJsonTabBtn')).show();\n return;\n }\n policyEditors.edit = state;\n renderPolicyEditor('edit');\n const editorTab = bootstrap.Tab.getOrCreateInstance(document.getElementById('editPolicyEditorTabBtn'));\n editorTab.show();\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error loading policy for editing: ' + error.message, 'error');\n const editModal = bootstrap.Modal.getInstance(document.getElementById('editPolicyModal'));\n if (editModal) editModal.hide();\n });\n }\n\n function updatePolicy() {\n if (!commitPolicyActiveTab('edit')) return;\n if (!confirmPolicyFieldDiscard('edit')) return;\n\n const policyName = document.getElementById('editPolicyName').value;\n const policyDocumentText = document.getElementById('editPolicyDocument').value;\n\n if (!policyName || !policyDocumentText) {\n showAlert('Please fill in all required fields', 'warning');\n return;\n }\n\n let policyDocument;\n try {\n policyDocument = JSON.parse(policyDocumentText);\n } catch (e) {\n showAlert('Invalid JSON in policy document: ' + e.message, 'error');\n return;\n }\n\n const requestData = {\n document: policyDocument\n };\n\n validatePolicyJSON(policyDocumentText, true).then(valid => {\n if (!valid) return;\n\n fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestData)\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Policy updated successfully!', 'success');\n const modal = bootstrap.Modal.getInstance(document.getElementById('editPolicyModal'));\n if (modal) modal.hide();\n location.reload(); // Refresh the page to show the updated policy\n } else {\n showAlert('Error updating policy: ' + (data.error || 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error updating policy: ' + error.message, 'error');\n });\n });\n }\n\n function validatePolicyDocument(which) {\n if (!commitPolicyActiveTab(which)) return;\n const policyText = document.getElementById(policyTextareaId(which)).value;\n validatePolicyJSON(policyText);\n }\n\n // Runs a policy document past the server's validator. Resolves to true\n // when it passes, and to false after alerting the user when it doesn't.\n // `quiet` suppresses the success alert for callers that go on to report\n // an outcome of their own.\n function validatePolicyJSON(policyText, quiet) {\n if (!policyText) {\n showAlert('Please enter a policy document first', 'warning');\n return Promise.resolve(false);\n }\n\n let policyDocument;\n try {\n policyDocument = JSON.parse(policyText);\n } catch (e) {\n showAlert('Invalid JSON: ' + e.message, 'error');\n return Promise.resolve(false);\n }\n\n return fetch(basePath('/api/object-store/policies/validate'), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ document: policyDocument })\n })\n .then(response => response.json().then(data => ({ ok: response.ok, data })))\n .then(({ ok, data }) => {\n if (ok && data.valid) {\n if (!quiet) {\n showAlert(data.message || 'Policy document is valid!', 'success');\n }\n return true;\n }\n showAlert('Invalid policy: ' + (data.error || 'unknown error'), 'error');\n return false;\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error validating policy: ' + error.message, 'error');\n return false;\n });\n }\n\n function deletePolicy(policyName) {\n showDeleteConfirm(policyName, function() {\n fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {\n method: 'DELETE'\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Policy deleted successfully!', 'success');\n location.reload();\n } else {\n showAlert('Error deleting policy: ' + (data.error || 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error deleting policy: ' + error.message, 'error');\n });\n });\n }\n </script>")if templ_7745c5c3_Err != nil {return templ_7745c5c3_Err}diff --git a/weed/admin/view/app/policy_action_suggestions.go b/weed/admin/view/app/policy_action_suggestions.gonew file mode 100644index 0000000000..608bc8eaf5--- /dev/null+++ b/weed/admin/view/app/policy_action_suggestions.go@@ -0,0 +1,107 @@+package app++import "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"++// PolicyActionSuggestions feeds the <datalist> used by the structured policy+// editor's Action inputs. This is an input-assistance aid, NOT a validation+// list: the editor accepts any action string typed by hand, since IAM policy+// actions are not restricted to this set (custom/future actions, wildcards+// like "s3:Get*", etc.).+var PolicyActionSuggestions = buildPolicyActionSuggestions()++func buildPolicyActionSuggestions() []string {+ return []string{+ // s3: actions, sourced from the constants used elsewhere for policy+ // evaluation (weed/s3api/s3_constants/s3_action_strings.go) so the+ // suggestion list can't drift from the strings the engine actually+ // understands.+ s3_constants.S3_ACTION_ALL,+ s3_constants.S3_ACTION_GET_OBJECT,+ s3_constants.S3_ACTION_PUT_OBJECT,+ s3_constants.S3_ACTION_DELETE_OBJECT,+ s3_constants.S3_ACTION_DELETE_OBJECT_VERSION,+ s3_constants.S3_ACTION_GET_OBJECT_VERSION,+ s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES,+ s3_constants.S3_ACTION_GET_OBJECT_ACL,+ s3_constants.S3_ACTION_PUT_OBJECT_ACL,+ s3_constants.S3_ACTION_GET_OBJECT_TAGGING,+ s3_constants.S3_ACTION_PUT_OBJECT_TAGGING,+ s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING,+ s3_constants.S3_ACTION_GET_OBJECT_RETENTION,+ s3_constants.S3_ACTION_PUT_OBJECT_RETENTION,+ s3_constants.S3_ACTION_GET_OBJECT_LEGAL_HOLD,+ s3_constants.S3_ACTION_PUT_OBJECT_LEGAL_HOLD,+ s3_constants.S3_ACTION_BYPASS_GOVERNANCE,+ s3_constants.S3_ACTION_CREATE_MULTIPART,+ s3_constants.S3_ACTION_UPLOAD_PART,+ s3_constants.S3_ACTION_COMPLETE_MULTIPART,+ s3_constants.S3_ACTION_ABORT_MULTIPART,+ s3_constants.S3_ACTION_UPLOAD_PART_COPY,+ s3_constants.S3_ACTION_LIST_PARTS,+ s3_constants.S3_ACTION_LIST_MULTIPART_UPLOADS,+ s3_constants.S3_ACTION_CREATE_BUCKET,+ s3_constants.S3_ACTION_DELETE_BUCKET,+ s3_constants.S3_ACTION_LIST_BUCKET,+ s3_constants.S3_ACTION_LIST_BUCKET_VERSIONS,+ s3_constants.S3_ACTION_GET_BUCKET_ACL,+ s3_constants.S3_ACTION_PUT_BUCKET_ACL,+ s3_constants.S3_ACTION_GET_BUCKET_POLICY,+ s3_constants.S3_ACTION_PUT_BUCKET_POLICY,+ s3_constants.S3_ACTION_DELETE_BUCKET_POLICY,+ s3_constants.S3_ACTION_GET_BUCKET_TAGGING,+ s3_constants.S3_ACTION_PUT_BUCKET_TAGGING,+ s3_constants.S3_ACTION_DELETE_BUCKET_TAGGING,+ s3_constants.S3_ACTION_GET_BUCKET_CORS,+ s3_constants.S3_ACTION_PUT_BUCKET_CORS,+ s3_constants.S3_ACTION_DELETE_BUCKET_CORS,+ s3_constants.S3_ACTION_GET_BUCKET_LIFECYCLE,+ s3_constants.S3_ACTION_PUT_BUCKET_LIFECYCLE,+ s3_constants.S3_ACTION_GET_BUCKET_VERSIONING,+ s3_constants.S3_ACTION_PUT_BUCKET_VERSIONING,+ s3_constants.S3_ACTION_GET_BUCKET_LOCATION,+ s3_constants.S3_ACTION_GET_BUCKET_NOTIFICATION,+ s3_constants.S3_ACTION_PUT_BUCKET_NOTIFICATION,+ s3_constants.S3_ACTION_GET_BUCKET_OBJECT_LOCK,+ s3_constants.S3_ACTION_PUT_BUCKET_OBJECT_LOCK,++ // s3tables: actions, sourced from weed/s3api/s3_constants so this list+ // can't drift from the strings the s3tables engine actually understands.+ s3_constants.S3TABLES_ACTION_ALL,+ s3_constants.S3TABLES_ACTION_CREATE_TABLE_BUCKET,+ s3_constants.S3TABLES_ACTION_GET_TABLE_BUCKET,+ s3_constants.S3TABLES_ACTION_LIST_TABLE_BUCKETS,+ s3_constants.S3TABLES_ACTION_DELETE_TABLE_BUCKET,+ s3_constants.S3TABLES_ACTION_PUT_TABLE_BUCKET_POLICY,+ s3_constants.S3TABLES_ACTION_GET_TABLE_BUCKET_POLICY,+ s3_constants.S3TABLES_ACTION_DELETE_TABLE_BUCKET_POLICY,+ s3_constants.S3TABLES_ACTION_CREATE_NAMESPACE,+ s3_constants.S3TABLES_ACTION_GET_NAMESPACE,+ s3_constants.S3TABLES_ACTION_UPDATE_NAMESPACE,+ s3_constants.S3TABLES_ACTION_LIST_NAMESPACES,+ s3_constants.S3TABLES_ACTION_DELETE_NAMESPACE,+ s3_constants.S3TABLES_ACTION_CREATE_TABLE,+ s3_constants.S3TABLES_ACTION_REGISTER_TABLE,+ s3_constants.S3TABLES_ACTION_GET_TABLE,+ s3_constants.S3TABLES_ACTION_LIST_TABLES,+ s3_constants.S3TABLES_ACTION_UPDATE_TABLE,+ s3_constants.S3TABLES_ACTION_DELETE_TABLE,+ s3_constants.S3TABLES_ACTION_RENAME_TABLE,+ s3_constants.S3TABLES_ACTION_CREATE_VIEW,+ s3_constants.S3TABLES_ACTION_GET_VIEW,+ s3_constants.S3TABLES_ACTION_LIST_VIEWS,+ s3_constants.S3TABLES_ACTION_UPDATE_VIEW,+ s3_constants.S3TABLES_ACTION_DELETE_VIEW,+ s3_constants.S3TABLES_ACTION_RENAME_VIEW,+ s3_constants.S3TABLES_ACTION_PUT_TABLE_POLICY,+ s3_constants.S3TABLES_ACTION_GET_TABLE_POLICY,+ s3_constants.S3TABLES_ACTION_DELETE_TABLE_POLICY,+ s3_constants.S3TABLES_ACTION_PUT_TABLE_BUCKET_MAINTENANCE_CONFIGURATION,+ s3_constants.S3TABLES_ACTION_GET_TABLE_BUCKET_MAINTENANCE_CONFIGURATION,+ s3_constants.S3TABLES_ACTION_PUT_TABLE_MAINTENANCE_CONFIGURATION,+ s3_constants.S3TABLES_ACTION_GET_TABLE_MAINTENANCE_CONFIGURATION,+ s3_constants.S3TABLES_ACTION_GET_TABLE_MAINTENANCE_JOB_STATUS,+ s3_constants.S3TABLES_ACTION_TAG_RESOURCE,+ s3_constants.S3TABLES_ACTION_LIST_TAGS_FOR_RESOURCE,+ s3_constants.S3TABLES_ACTION_UNTAG_RESOURCE,+ }+}diff --git a/weed/admin/view/app/policy_action_suggestions_test.go b/weed/admin/view/app/policy_action_suggestions_test.gonew file mode 100644index 0000000000..d45cee4204--- /dev/null+++ b/weed/admin/view/app/policy_action_suggestions_test.go@@ -0,0 +1,38 @@+package app++import (+ "strings"+ "testing"+)++func TestPolicyActionSuggestions_NotEmpty(t *testing.T) {+ if len(PolicyActionSuggestions) == 0 {+ t.Fatal("expected at least one suggestion")+ }+}++func TestPolicyActionSuggestions_NoDuplicates(t *testing.T) {+ seen := make(map[string]bool, len(PolicyActionSuggestions))+ for _, action := range PolicyActionSuggestions {+ if seen[action] {+ t.Errorf("duplicate action suggestion: %q", action)+ }+ seen[action] = true+ }+}++func TestPolicyActionSuggestions_AllPrefixed(t *testing.T) {+ for _, action := range PolicyActionSuggestions {+ if !strings.HasPrefix(action, "s3:") && !strings.HasPrefix(action, "s3tables:") {+ t.Errorf("action suggestion %q is not prefixed with a known service", action)+ }+ }+}++func TestPolicyActionSuggestions_NoEmptyStrings(t *testing.T) {+ for i, action := range PolicyActionSuggestions {+ if strings.TrimSpace(action) == "" {+ t.Errorf("suggestion at index %d is empty", i)+ }+ }+}diff --git a/weed/s3api/s3_constants/s3_action_strings.go b/weed/s3api/s3_constants/s3_action_strings.goindex 5d96ba2c8d..037324ae5d 100644--- a/weed/s3api/s3_constants/s3_action_strings.go+++ b/weed/s3api/s3_constants/s3_action_strings.go@@ -84,3 +84,64 @@ const (// Wildcard for all S3 actionsS3_ACTION_ALL = "s3:*")++// S3 Tables action strings for policy evaluation.+// Source of truth for the operation names: the dispatch switch in+// weed/s3api/s3tables/handler.go. Keep this list in sync with that switch+// when operations are added, renamed, or removed.+const (+ // Table bucket operations+ S3TABLES_ACTION_CREATE_TABLE_BUCKET = "s3tables:CreateTableBucket"+ S3TABLES_ACTION_GET_TABLE_BUCKET = "s3tables:GetTableBucket"+ S3TABLES_ACTION_LIST_TABLE_BUCKETS = "s3tables:ListTableBuckets"+ S3TABLES_ACTION_DELETE_TABLE_BUCKET = "s3tables:DeleteTableBucket"++ // Table bucket policy operations+ S3TABLES_ACTION_PUT_TABLE_BUCKET_POLICY = "s3tables:PutTableBucketPolicy"+ S3TABLES_ACTION_GET_TABLE_BUCKET_POLICY = "s3tables:GetTableBucketPolicy"+ S3TABLES_ACTION_DELETE_TABLE_BUCKET_POLICY = "s3tables:DeleteTableBucketPolicy"++ // Namespace operations+ S3TABLES_ACTION_CREATE_NAMESPACE = "s3tables:CreateNamespace"+ S3TABLES_ACTION_GET_NAMESPACE = "s3tables:GetNamespace"+ S3TABLES_ACTION_UPDATE_NAMESPACE = "s3tables:UpdateNamespace"+ S3TABLES_ACTION_LIST_NAMESPACES = "s3tables:ListNamespaces"+ S3TABLES_ACTION_DELETE_NAMESPACE = "s3tables:DeleteNamespace"++ // Table operations+ S3TABLES_ACTION_CREATE_TABLE = "s3tables:CreateTable"+ S3TABLES_ACTION_REGISTER_TABLE = "s3tables:RegisterTable"+ S3TABLES_ACTION_GET_TABLE = "s3tables:GetTable"+ S3TABLES_ACTION_LIST_TABLES = "s3tables:ListTables"+ S3TABLES_ACTION_UPDATE_TABLE = "s3tables:UpdateTable"+ S3TABLES_ACTION_DELETE_TABLE = "s3tables:DeleteTable"+ S3TABLES_ACTION_RENAME_TABLE = "s3tables:RenameTable"++ // View operations+ S3TABLES_ACTION_CREATE_VIEW = "s3tables:CreateView"+ S3TABLES_ACTION_GET_VIEW = "s3tables:GetView"+ S3TABLES_ACTION_LIST_VIEWS = "s3tables:ListViews"+ S3TABLES_ACTION_UPDATE_VIEW = "s3tables:UpdateView"+ S3TABLES_ACTION_DELETE_VIEW = "s3tables:DeleteView"+ S3TABLES_ACTION_RENAME_VIEW = "s3tables:RenameView"++ // Table policy operations+ S3TABLES_ACTION_PUT_TABLE_POLICY = "s3tables:PutTablePolicy"+ S3TABLES_ACTION_GET_TABLE_POLICY = "s3tables:GetTablePolicy"+ S3TABLES_ACTION_DELETE_TABLE_POLICY = "s3tables:DeleteTablePolicy"++ // Maintenance configuration operations+ S3TABLES_ACTION_PUT_TABLE_BUCKET_MAINTENANCE_CONFIGURATION = "s3tables:PutTableBucketMaintenanceConfiguration"+ S3TABLES_ACTION_GET_TABLE_BUCKET_MAINTENANCE_CONFIGURATION = "s3tables:GetTableBucketMaintenanceConfiguration"+ S3TABLES_ACTION_PUT_TABLE_MAINTENANCE_CONFIGURATION = "s3tables:PutTableMaintenanceConfiguration"+ S3TABLES_ACTION_GET_TABLE_MAINTENANCE_CONFIGURATION = "s3tables:GetTableMaintenanceConfiguration"+ S3TABLES_ACTION_GET_TABLE_MAINTENANCE_JOB_STATUS = "s3tables:GetTableMaintenanceJobStatus"++ // Tagging operations+ S3TABLES_ACTION_TAG_RESOURCE = "s3tables:TagResource"+ S3TABLES_ACTION_LIST_TAGS_FOR_RESOURCE = "s3tables:ListTagsForResource"+ S3TABLES_ACTION_UNTAG_RESOURCE = "s3tables:UntagResource"++ // Wildcard for all S3 Tables actions+ S3TABLES_ACTION_ALL = "s3tables:*"+)