Skip to content

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.

Manage bucket policies via the admin ui (#10895)

Mathieu Arnolde931cccc7b75
diff --git a/weed/admin/dash/admin_server.go b/weed/admin/dash/admin_server.go
index c76815736a..ba70b5e09f 100644
--- a/weed/admin/dash/admin_server.go
+++ b/weed/admin/dash/admin_server.go
@@ -2,6 +2,7 @@ package dash
import (
"context"
+ "encoding/json"
"errors"
"fmt"
"io"
@@ -34,6 +35,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/s3api"
"github.com/seaweedfs/seaweedfs/weed/s3api/lifecycle_xml"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
@@ -888,6 +890,7 @@ func (s *AdminServer) GetS3Buckets() ([]S3Bucket, error) {
Owner: owner,
LifecycleRuleCount: lifecycleRuleCount,
LifecycleEnabledCount: lifecycleEnabledCount,
+ PolicyStatementCount: extractPolicyStatementCountFromEntry(resp.Entry),
}
buckets = append(buckets, bucket)
}
@@ -993,6 +996,7 @@ func (s *AdminServer) GetBucketDetails(bucketName string) (*BucketDetails, error
details.Bucket.ObjectLockDuration = objectLockDuration
details.Bucket.Owner = owner
details.Bucket.LifecycleRuleCount, details.Bucket.LifecycleEnabledCount = extractLifecycleCountsFromEntry(bucketResp.Entry)
+ details.Bucket.PolicyStatementCount = extractPolicyStatementCountFromEntry(bucketResp.Entry)
return nil
})
@@ -2106,6 +2110,21 @@ func extractLifecycleCountsFromEntry(entry *filer_pb.Entry) (ruleCount, enabledC
return
}
+// extractPolicyStatementCountFromEntry returns the number of statements in
+// the bucket's policy, or 0 if it has none or the stored JSON can't be
+// parsed. Forgiving on parse failure, same as extractLifecycleCountsFromEntry.
+func extractPolicyStatementCountFromEntry(entry *filer_pb.Entry) int {
+ policyJSON := entry.Extended[s3api.BUCKET_POLICY_METADATA_KEY]
+ if len(policyJSON) == 0 {
+ return 0
+ }
+ var doc policy_engine.PolicyDocument
+ if err := json.Unmarshal(policyJSON, &doc); err != nil {
+ return 0
+ }
+ return len(doc.Statement)
+}
+
// GetConfigPersistence returns the config persistence manager
func (as *AdminServer) GetConfigPersistence() *ConfigPersistence {
return as.configPersistence
diff --git a/weed/admin/dash/bucket_management.go b/weed/admin/dash/bucket_management.go
index 2e6072e529..07e649a509 100644
--- a/weed/admin/dash/bucket_management.go
+++ b/weed/admin/dash/bucket_management.go
@@ -13,6 +13,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
)
@@ -257,6 +258,100 @@ func validateBucketLifecycleRules(rules []BucketLifecycleRule) error {
return nil
}
+// ShowBucketPolicy returns the policy document for a specific bucket, or
+// {"bucket": ..., "policy": null} if the bucket has none.
+func (s *AdminServer) ShowBucketPolicy(w http.ResponseWriter, r *http.Request) {
+ bucketName := mux.Vars(r)["bucket"]
+ if bucketName == "" {
+ writeJSONError(w, http.StatusBadRequest, "Bucket name is required")
+ return
+ }
+
+ policy, err := s.GetBucketPolicy(bucketName)
+ if err != nil {
+ writeJSONError(w, bucketPolicyErrorStatus(err), "Failed to get bucket policy: "+err.Error())
+ return
+ }
+
+ writeJSON(w, http.StatusOK, map[string]interface{}{
+ "bucket": bucketName,
+ "policy": policy,
+ })
+}
+
+// UpdateBucketPolicy replaces the bucket policy for a bucket.
+func (s *AdminServer) UpdateBucketPolicy(w http.ResponseWriter, r *http.Request) {
+ if !requireSessionCSRFToken(w, r) {
+ return
+ }
+
+ bucketName := mux.Vars(r)["bucket"]
+ if bucketName == "" {
+ writeJSONError(w, http.StatusBadRequest, "Bucket name is required")
+ return
+ }
+
+ var req struct {
+ Policy *policy_engine.PolicyDocument `json:"policy"`
+ }
+ if err := decodeJSONBody(newJSONMaxReader(w, r), &req); err != nil {
+ writeJSONError(w, http.StatusBadRequest, "Invalid request: "+err.Error())
+ return
+ }
+ if req.Policy == nil {
+ writeJSONError(w, http.StatusBadRequest, "policy is required; use DELETE to clear a bucket policy")
+ return
+ }
+
+ if err := s.SetBucketPolicy(bucketName, req.Policy); err != nil {
+ writeJSONError(w, bucketPolicyErrorStatus(err), "Failed to update bucket policy: "+err.Error())
+ return
+ }
+
+ writeJSON(w, http.StatusOK, map[string]interface{}{
+ "message": "Bucket policy updated successfully",
+ "bucket": bucketName,
+ })
+}
+
+// RemoveBucketPolicy clears the bucket policy for a bucket. Named
+// "Remove", not "Delete", because (*AdminServer).DeleteBucketPolicy is the
+// data-layer method this handler calls.
+func (s *AdminServer) RemoveBucketPolicy(w http.ResponseWriter, r *http.Request) {
+ if !requireSessionCSRFToken(w, r) {
+ return
+ }
+
+ bucketName := mux.Vars(r)["bucket"]
+ if bucketName == "" {
+ writeJSONError(w, http.StatusBadRequest, "Bucket name is required")
+ return
+ }
+
+ if err := s.DeleteBucketPolicy(bucketName); err != nil {
+ writeJSONError(w, bucketPolicyErrorStatus(err), "Failed to delete bucket policy: "+err.Error())
+ return
+ }
+
+ writeJSON(w, http.StatusOK, map[string]interface{}{
+ "message": "Bucket policy deleted successfully",
+ "bucket": bucketName,
+ })
+}
+
+// bucketPolicyErrorStatus keeps a request for a bucket that does not exist,
+// or an invalid policy document, out of the 5xx bucket where a client
+// would retry it. Mirrors bucketLifecycleErrorStatus.
+func bucketPolicyErrorStatus(err error) int {
+ if errors.Is(err, ErrBucketNotFound) {
+ return http.StatusNotFound
+ }
+ if errors.Is(err, ErrInvalidBucketPolicy) {
+ return http.StatusBadRequest
+ }
+ return http.StatusInternalServerError
+}
+
// CreateBucket creates a new S3 bucket
func (s *AdminServer) CreateBucket(w http.ResponseWriter, r *http.Request) {
var req CreateBucketRequest
diff --git a/weed/admin/dash/bucket_policy.go b/weed/admin/dash/bucket_policy.go
new file mode 100644
index 0000000000..0a860f919b
--- /dev/null
+++ b/weed/admin/dash/bucket_policy.go
@@ -0,0 +1,192 @@
+package dash
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+
+ "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
+ "github.com/seaweedfs/seaweedfs/weed/s3api"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
+)
+
+// MaxBucketPolicySize mirrors AWS S3's 20 KB bucket-policy limit. This is an
+// admin-side cap the S3 gateway does not itself enforce; it can only reject
+// a policy the gateway would have accepted, never disagree about one
+// already stored, so it cannot desync admin and S3 behavior.
+const MaxBucketPolicySize = 20 * 1024
+
+// ErrInvalidBucketPolicy wraps a validation failure from SetBucketPolicy so
+// callers (the HTTP handler) can map it to 400 instead of 500 without
+// resorting to matching on the error string.
+var ErrInvalidBucketPolicy = errors.New("invalid bucket policy")
+
+// GetBucketPolicy returns the policy document stored on a bucket's filer
+// entry, or (nil, nil) if the bucket has no policy — that is not an error,
+// it just means the caller (e.g. the admin UI) should show an empty editor
+// instead of special-casing a 404.
+func (s *AdminServer) GetBucketPolicy(bucketName string) (*policy_engine.PolicyDocument, error) {
+ filerConfig, err := s.getFilerConfig()
+ if err != nil {
+ return nil, fmt.Errorf("get filer configuration: %w", err)
+ }
+
+ var doc *policy_engine.PolicyDocument
+ err = s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
+ resp, err := filer_pb.LookupEntry(context.Background(), client, &filer_pb.LookupDirectoryEntryRequest{
+ Directory: filerConfig.BucketsPath,
+ Name: bucketName,
+ })
+ if err != nil {
+ if errors.Is(err, filer_pb.ErrNotFound) {
+ return fmt.Errorf("%w: %s", ErrBucketNotFound, bucketName)
+ }
+ return fmt.Errorf("look up bucket %s: %w", bucketName, err)
+ }
+
+ policyJSON := resp.Entry.Extended[s3api.BUCKET_POLICY_METADATA_KEY]
+ if len(policyJSON) == 0 {
+ return nil
+ }
+
+ var parsed policy_engine.PolicyDocument
+ if err := json.Unmarshal(policyJSON, &parsed); err != nil {
+ return fmt.Errorf("parse stored bucket policy: %w", err)
+ }
+ doc = &parsed
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return doc, nil
+}
+
+// SetBucketPolicy validates and stores a bucket policy, applying the exact
+// same validation the S3 gateway's PutBucketPolicy enforces
+// (policy_engine.ValidatePolicy + policy_engine.ValidateBucketPolicy), so
+// the admin UI and the S3 API never disagree about what's a valid policy.
+//
+// Propagation to every S3 gateway is automatic: writing the
+// s3-bucket-policy extended attribute drives the filer metadata log, which
+// each gateway's onBucketMetadataChange subscription already watches to
+// rebuild its bucket policy cache. No separate notify step is needed here.
+//
+// Note: PutBucketPolicyHandler on the S3 gateway also mirrors the policy
+// into the IAM policy store under "bucket-policy:<bucket>"
+// (iam_manager.go's UpdateBucketPolicy), but its delete counterpart
+// (removeBucketPolicyFromIAM) is an unimplemented TODO — so that mirror is
+// already unreliable after any S3-side DeleteBucketPolicy. The admin write
+// path deliberately does not replicate it: doing so would only deepen an
+// existing inconsistency, and admin has no handle on the S3 gateway's
+// iamManager anyway. See the TODO in
+// weed/s3api/s3api_bucket_policy_handlers.go for the follow-up.
+func (s *AdminServer) SetBucketPolicy(bucketName string, doc *policy_engine.PolicyDocument) error {
+ if err := policy_engine.ValidatePolicy(doc); err != nil {
+ return fmt.Errorf("%w: %w", ErrInvalidBucketPolicy, err)
+ }
+ if err := policy_engine.ValidateBucketPolicy(doc, bucketName); err != nil {
+ return fmt.Errorf("%w: %w", ErrInvalidBucketPolicy, err)
+ }
+
+ policyJSON, err := json.Marshal(doc)
+ if err != nil {
+ return fmt.Errorf("marshal policy document: %w", err)
+ }
+ if len(policyJSON) > MaxBucketPolicySize {
+ return fmt.Errorf("%w: bucket policy is %d bytes, which exceeds the %d byte limit", ErrInvalidBucketPolicy, len(policyJSON), MaxBucketPolicySize)
+ }
+
+ filerConfig, err := s.getFilerConfig()
+ if err != nil {
+ return fmt.Errorf("get filer configuration: %w", err)
+ }
+
+ return s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
+ // PATCH_EXTENDED is a no-op on a missing entry, so the existence
+ // check has to happen here rather than fall out of the write.
+ if _, err := filer_pb.LookupEntry(context.Background(), client, &filer_pb.LookupDirectoryEntryRequest{
+ Directory: filerConfig.BucketsPath,
+ Name: bucketName,
+ }); err != nil {
+ if errors.Is(err, filer_pb.ErrNotFound) {
+ return fmt.Errorf("%w: %s", ErrBucketNotFound, bucketName)
+ }
+ return fmt.Errorf("look up bucket %s: %w", bucketName, err)
+ }
+
+ bucketPath := filerConfig.BucketsPath + "/" + bucketName
+ resp, err := client.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
+ LockKey: bucketPath,
+ RouteKey: s3_constants.ObjectWriteRouteKeyPrefix + bucketPath,
+ Mutations: []*filer_pb.ObjectMutation{bucketPolicyMutation(filerConfig.BucketsPath, bucketName, policyJSON)},
+ })
+ if err != nil {
+ return fmt.Errorf("failed to update bucket policy: %w", err)
+ }
+ if resp.Error != "" {
+ return fmt.Errorf("failed to update bucket policy: %s", resp.Error)
+ }
+ return nil
+ })
+}
+
+// DeleteBucketPolicy clears the bucket policy stored on a bucket's filer
+// entry. Deleting a policy that doesn't exist is a success, matching
+// DeleteBucketLifecycle's idempotent behavior.
+func (s *AdminServer) DeleteBucketPolicy(bucketName string) error {
+ filerConfig, err := s.getFilerConfig()
+ if err != nil {
+ return fmt.Errorf("get filer configuration: %w", err)
+ }
+
+ return s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
+ if _, err := filer_pb.LookupEntry(context.Background(), client, &filer_pb.LookupDirectoryEntryRequest{
+ Directory: filerConfig.BucketsPath,
+ Name: bucketName,
+ }); err != nil {
+ if errors.Is(err, filer_pb.ErrNotFound) {
+ return fmt.Errorf("%w: %s", ErrBucketNotFound, bucketName)
+ }
+ return fmt.Errorf("look up bucket %s: %w", bucketName, err)
+ }
+
+ bucketPath := filerConfig.BucketsPath + "/" + bucketName
+ resp, err := client.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
+ LockKey: bucketPath,
+ RouteKey: s3_constants.ObjectWriteRouteKeyPrefix + bucketPath,
+ Mutations: []*filer_pb.ObjectMutation{bucketPolicyMutation(filerConfig.BucketsPath, bucketName, nil)},
+ })
+ if err != nil {
+ return fmt.Errorf("failed to delete bucket policy: %w", err)
+ }
+ if resp.Error != "" {
+ return fmt.Errorf("failed to delete bucket policy: %s", resp.Error)
+ }
+ return nil
+ })
+}
+
+// bucketPolicyMutation patches only the policy key rather than writing the
+// whole entry back: the filer re-reads and merges under the bucket path
+// lock, so a concurrent owner/quota/versioning/lifecycle change is
+// preserved instead of being reverted by a stale snapshot. Same pattern as
+// bucketLifecycleMutation. A nil/empty policyJSON clears the key.
+func bucketPolicyMutation(bucketsPath, bucketName string, policyJSON []byte) *filer_pb.ObjectMutation {
+ mutation := &filer_pb.ObjectMutation{
+ Type: filer_pb.ObjectMutation_PATCH_EXTENDED,
+ Directory: bucketsPath,
+ Name: bucketName,
+ }
+ if len(policyJSON) > 0 {
+ mutation.SetExtended = map[string][]byte{
+ s3api.BUCKET_POLICY_METADATA_KEY: policyJSON,
+ }
+ return mutation
+ }
+ mutation.DeleteExtended = []string{s3api.BUCKET_POLICY_METADATA_KEY}
+ return mutation
+}
diff --git a/weed/admin/dash/bucket_policy_test.go b/weed/admin/dash/bucket_policy_test.go
new file mode 100644
index 0000000000..df8c19ce3f
--- /dev/null
+++ b/weed/admin/dash/bucket_policy_test.go
@@ -0,0 +1,168 @@
+package dash
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
+ "github.com/seaweedfs/seaweedfs/weed/s3api"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
+)
+
+func validBucketPolicyJSON(bucket string) []byte {
+ return []byte(fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*"}]}`, bucket))
+}
+
+func validBucketPolicyDoc(bucket string) *policy_engine.PolicyDocument {
+ var doc policy_engine.PolicyDocument
+ if err := json.Unmarshal(validBucketPolicyJSON(bucket), &doc); err != nil {
+ panic(err)
+ }
+ return &doc
+}
+
+func TestBucketPolicyMutation_SetsPolicy(t *testing.T) {
+ policyJSON := validBucketPolicyJSON("mybucket")
+ m := bucketPolicyMutation("/buckets", "mybucket", policyJSON)
+
+ if m.Type != filer_pb.ObjectMutation_PATCH_EXTENDED {
+ t.Fatalf("expected a PATCH_EXTENDED mutation, got %v", m.Type)
+ }
+ if m.Directory != "/buckets" || m.Name != "mybucket" {
+ t.Fatalf("expected the mutation to target /buckets/mybucket, got %s/%s", m.Directory, m.Name)
+ }
+ if got := m.SetExtended[s3api.BUCKET_POLICY_METADATA_KEY]; string(got) != string(policyJSON) {
+ t.Fatalf("expected the policy key to carry the marshaled document, got %q", got)
+ }
+ if len(m.DeleteExtended) != 0 {
+ t.Fatalf("expected no key deletions when saving a policy, got %v", m.DeleteExtended)
+ }
+}
+
+func TestBucketPolicyMutation_ClearsKey(t *testing.T) {
+ m := bucketPolicyMutation("/buckets", "mybucket", nil)
+
+ if len(m.SetExtended) != 0 {
+ t.Fatalf("expected no key writes when clearing, got %v", m.SetExtended)
+ }
+ if len(m.DeleteExtended) != 1 || m.DeleteExtended[0] != s3api.BUCKET_POLICY_METADATA_KEY {
+ t.Fatalf("expected only the policy key to be cleared, got %v", m.DeleteExtended)
+ }
+}
+
+// A whole-entry write would have carried the rest of the bucket entry with
+// it; the patch must name only the key it owns, so a concurrent owner,
+// quota, or lifecycle change survives.
+func TestBucketPolicyMutation_TouchesOnlyPolicyKey(t *testing.T) {
+ for _, m := range []*filer_pb.ObjectMutation{
+ bucketPolicyMutation("/buckets", "mybucket", validBucketPolicyJSON("mybucket")),
+ bucketPolicyMutation("/buckets", "mybucket", nil),
+ } {
+ if m.Entry != nil {
+ t.Fatal("expected the mutation to carry no entry snapshot")
+ }
+ if m.SetContent {
+ t.Fatal("expected the mutation to leave entry content alone")
+ }
+ for k := range m.SetExtended {
+ if k != s3api.BUCKET_POLICY_METADATA_KEY {
+ t.Fatalf("unexpected key written: %s", k)
+ }
+ }
+ for _, k := range m.DeleteExtended {
+ if k != s3api.BUCKET_POLICY_METADATA_KEY {
+ t.Fatalf("unexpected key deleted: %s", k)
+ }
+ }
+ }
+}
+
+func TestExtractPolicyStatementCountFromEntry(t *testing.T) {
+ tests := []struct {
+ name string
+ entry *filer_pb.Entry
+ want int
+ }{
+ {"no extended attrs", &filer_pb.Entry{}, 0},
+ {"absent key", &filer_pb.Entry{Extended: map[string][]byte{"other": []byte("x")}}, 0},
+ {"one statement", &filer_pb.Entry{Extended: map[string][]byte{
+ s3api.BUCKET_POLICY_METADATA_KEY: validBucketPolicyJSON("b"),
+ }}, 1},
+ {"three statements", &filer_pb.Entry{Extended: map[string][]byte{
+ s3api.BUCKET_POLICY_METADATA_KEY: []byte(`{"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::b/*"},
+ {"Effect":"Allow","Principal":"*","Action":"s3:PutObject","Resource":"arn:aws:s3:::b/*"},
+ {"Effect":"Deny","Principal":"*","Action":"s3:DeleteObject","Resource":"arn:aws:s3:::b/*"}
+ ]}`),
+ }}, 3},
+ {"garbage bytes", &filer_pb.Entry{Extended: map[string][]byte{
+ s3api.BUCKET_POLICY_METADATA_KEY: []byte("not json"),
+ }}, 0},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := extractPolicyStatementCountFromEntry(tt.entry); got != tt.want {
+ t.Errorf("extractPolicyStatementCountFromEntry() = %d, want %d", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestBucketPolicyErrorStatus(t *testing.T) {
+ if got := bucketPolicyErrorStatus(fmt.Errorf("%w: mybucket", ErrBucketNotFound)); got != http.StatusNotFound {
+ t.Fatalf("expected a missing bucket to map to 404, got %d", got)
+ }
+ if got := bucketPolicyErrorStatus(fmt.Errorf("%w: bad statement", ErrInvalidBucketPolicy)); got != http.StatusBadRequest {
+ t.Fatalf("expected an invalid policy to map to 400, got %d", got)
+ }
+ if got := bucketPolicyErrorStatus(errors.New("filer unreachable")); got != http.StatusInternalServerError {
+ t.Fatalf("expected an unrelated failure to stay 500, got %d", got)
+ }
+}
+
+func TestSetBucketPolicy_RejectsOversized(t *testing.T) {
+ // A resource list long enough to blow the cap: this must fail before
+ // any filer call, which is what makes it testable without one.
+ doc := validBucketPolicyDoc("mybucket")
+ doc.Statement[0].Sid = strings.Repeat("x", MaxBucketPolicySize+1)
+
+ err := (&AdminServer{}).SetBucketPolicy("mybucket", doc)
+ if err == nil {
+ t.Fatal("expected an oversized bucket policy to be rejected")
+ }
+ if !errors.Is(err, ErrInvalidBucketPolicy) {
+ t.Fatalf("expected an ErrInvalidBucketPolicy, got: %v", err)
+ }
+}
+
+func TestSetBucketPolicy_RejectsForeignResource(t *testing.T) {
+ // Proves the shared policy_engine.ValidateBucketPolicy validator is
+ // actually wired in: this is exactly the check the S3 gateway applies.
+ doc := validBucketPolicyDoc("mybucket")
+ doc.Statement[0].Resource = policy_engine.NewStringOrStringSlicePtr("arn:aws:s3:::other-bucket/*")
+
+ err := (&AdminServer{}).SetBucketPolicy("mybucket", doc)
+ if err == nil {
+ t.Fatal("expected a policy referencing a different bucket to be rejected")
+ }
+ if !errors.Is(err, ErrInvalidBucketPolicy) {
+ t.Fatalf("expected an ErrInvalidBucketPolicy, got: %v", err)
+ }
+}
+
+func TestSetBucketPolicy_RejectsMissingPrincipal(t *testing.T) {
+ doc := validBucketPolicyDoc("mybucket")
+ doc.Statement[0].Principal = nil
+
+ err := (&AdminServer{}).SetBucketPolicy("mybucket", doc)
+ if err == nil {
+ t.Fatal("expected a policy with no Principal to be rejected")
+ }
+ if !errors.Is(err, ErrInvalidBucketPolicy) {
+ t.Fatalf("expected an ErrInvalidBucketPolicy, got: %v", err)
+ }
+}
diff --git a/weed/admin/dash/s3tables_management.go b/weed/admin/dash/s3tables_management.go
index d1f1c641b3..78c35bb037 100644
--- a/weed/admin/dash/s3tables_management.go
+++ b/weed/admin/dash/s3tables_management.go
@@ -37,6 +37,12 @@ type S3TablesBucketSummary struct {
// Format is empty for a bucket created before formats were declared. Such a
// bucket takes tables of either format, which is what it always did.
Format string `json:"format,omitempty"`
+ // PolicyStatementCount is the number of statements in the table bucket's
+ // resource policy, or 0 if it has none. Unrelated to the S3 bucket
+ // policy mechanism (policy_engine.PolicyDocument / s3-bucket-policy):
+ // S3 Tables stores its own s3tables.PolicyDocument under the
+ // s3tables.policy extended attribute.
+ PolicyStatementCount int `json:"policy_statement_count"`
}
type S3TablesNamespacesData struct {
@@ -144,11 +150,12 @@ func (s *AdminServer) GetS3TablesBucketsData(ctx context.Context) (S3TablesBucke
continue
}
buckets = append(buckets, S3TablesBucketSummary{
- ARN: arn,
- Name: entry.Entry.Name,
- OwnerAccountID: metadata.OwnerAccountID,
- CreatedAt: metadata.CreatedAt,
- Format: metadata.Format,
+ ARN: arn,
+ Name: entry.Entry.Name,
+ OwnerAccountID: metadata.OwnerAccountID,
+ CreatedAt: metadata.CreatedAt,
+ Format: metadata.Format,
+ PolicyStatementCount: extractS3TablesPolicyStatementCountFromEntry(entry.Entry),
})
}
return nil
@@ -165,6 +172,23 @@ func (s *AdminServer) GetS3TablesBucketsData(ctx context.Context) (S3TablesBucke
}, nil
}
+// extractS3TablesPolicyStatementCountFromEntry returns the number of
+// statements in the table bucket's resource policy, or 0 if it has none or
+// the stored JSON can't be parsed. Forgiving on parse failure, matching
+// extractPolicyStatementCountFromEntry (the S3 bucket policy equivalent in
+// admin_server.go, which is a different, unrelated policy mechanism).
+func extractS3TablesPolicyStatementCountFromEntry(entry *filer_pb.Entry) int {
+ policyJSON := entry.Extended[s3tables.ExtendedKeyPolicy]
+ if len(policyJSON) == 0 {
+ return 0
+ }
+ var doc s3tables.PolicyDocument
+ if err := json.Unmarshal(policyJSON, &doc); err != nil {
+ return 0
+ }
+ return len(doc.Statement)
+}
+
// observedRowCounts collects what workers last reported for these tables. For a
// format admin cannot read, this is the only row count that exists.
func (s *AdminServer) observedRowCounts(bucketArn string, namespaceParts []string, tables []s3tables.TableSummary) map[string]string {
diff --git a/weed/admin/dash/types.go b/weed/admin/dash/types.go
index a161f8bf79..b30da79612 100644
--- a/weed/admin/dash/types.go
+++ b/weed/admin/dash/types.go
@@ -98,6 +98,12 @@ type S3Bucket struct {
LifecycleRuleCount int `json:"lifecycle_rule_count"`
LifecycleEnabledCount int `json:"lifecycle_enabled_count"`
+
+ // PolicyStatementCount is the number of statements in the bucket policy,
+ // or 0 if the bucket has none. A policy document can't have zero
+ // statements (see policy_engine.ValidatePolicy), so >0 is a faithful
+ // "has a policy" flag.
+ PolicyStatementCount int `json:"policy_statement_count"`
}
type S3Object struct {
diff --git a/weed/admin/handlers/admin_handlers.go b/weed/admin/handlers/admin_handlers.go
index 767790764f..67131b4b7b 100644
--- a/weed/admin/handlers/admin_handlers.go
+++ b/weed/admin/handlers/admin_handlers.go
@@ -183,6 +183,9 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) {
s3Api.Handle("/buckets/{bucket}/lifecycle", wrapWrite(h.adminServer.DeleteBucketLifecycle)).Methods(http.MethodDelete)
s3Api.Handle("/buckets/{bucket}/quota", wrapWrite(h.adminServer.UpdateBucketQuota)).Methods(http.MethodPut)
s3Api.Handle("/buckets/{bucket}/owner", wrapWrite(h.adminServer.UpdateBucketOwner)).Methods(http.MethodPut)
+ s3Api.HandleFunc("/buckets/{bucket}/policy", h.adminServer.ShowBucketPolicy).Methods(http.MethodGet)
+ s3Api.Handle("/buckets/{bucket}/policy", wrapWrite(h.adminServer.UpdateBucketPolicy)).Methods(http.MethodPut)
+ s3Api.Handle("/buckets/{bucket}/policy", wrapWrite(h.adminServer.RemoveBucketPolicy)).Methods(http.MethodDelete)
usersApi := api.PathPrefix("/users").Subrouter()
usersApi.HandleFunc("", h.userHandlers.GetUsers).Methods(http.MethodGet)
diff --git a/weed/admin/handlers/admin_handlers_routes_test.go b/weed/admin/handlers/admin_handlers_routes_test.go
index 9cbd355281..1cc0728cad 100644
--- a/weed/admin/handlers/admin_handlers_routes_test.go
+++ b/weed/admin/handlers/admin_handlers_routes_test.go
@@ -62,6 +62,26 @@ func TestSetupRoutes_RegistersBucketLifecycleAPI_WithAuth(t *testing.T) {
assertHasRoute(t, router, http.MethodDelete, "/api/s3/buckets/example/lifecycle")
}
+func TestSetupRoutes_RegistersBucketPolicyAPI_NoAuth(t *testing.T) {
+ router := mux.NewRouter()
+
+ newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)
+
+ assertHasRoute(t, router, http.MethodGet, "/api/s3/buckets/example/policy")
+ assertHasRoute(t, router, http.MethodPut, "/api/s3/buckets/example/policy")
+ assertHasRoute(t, router, http.MethodDelete, "/api/s3/buckets/example/policy")
+}
+
+func TestSetupRoutes_RegistersBucketPolicyAPI_WithAuth(t *testing.T) {
+ router := mux.NewRouter()
+
+ newRouteTestAdminHandlers().SetupRoutes(router, true, "admin", "password", "", "", true)
+
+ assertHasRoute(t, router, http.MethodGet, "/api/s3/buckets/example/policy")
+ assertHasRoute(t, router, http.MethodPut, "/api/s3/buckets/example/policy")
+ assertHasRoute(t, router, http.MethodDelete, "/api/s3/buckets/example/policy")
+}
+
func TestSetupRoutes_RegistersPolicyAPI_NoAuth(t *testing.T) {
router := mux.NewRouter()
diff --git a/weed/admin/static/js/policy_editor.js b/weed/admin/static/js/policy_editor.js
new file mode 100644
index 0000000000..0f914ed776
--- /dev/null
+++ b/weed/admin/static/js/policy_editor.js
@@ -0,0 +1,886 @@
+// Shared visual policy editor: renders and edits an IAM/bucket policy
+// document (Version + Statement list) via a structured form alongside a
+// raw-JSON tab, kept in sync in both directions.
+//
+// Extracted from weed/admin/view/app/policies.templ (the IAM policy
+// management page), which was its original and, for a while, only
+// consumer. Any page embedding this editor must first render the shared
+// datalists (see the PolicyDatalists templ component in
+// weed/admin/view/app/policy_datalists.templ) and load this script after
+// admin.js (for basePath/escapeHtml) and modal-alerts.js (for showAlert).
+//
+// Usage: call registerPolicyEditor(which, config) once to declare an
+// editor instance (see its doc comment for the id conventions and
+// config knobs), then setupPolicyEditor(which) once to wire up its DOM
+// listeners. which is an arbitrary string ("create", "edit",
+// "bucketPolicy", ...) that namespaces one editor instance's DOM ids and
+// state from another's on the same page.
+
+// Per-`which` editor configuration. See registerPolicyEditor.
+const POLICY_EDITOR_CONFIG = {};
+
+// registerPolicyEditor declares (or redeclares) the configuration for one
+// editor instance. Call before setupPolicyEditor(which), and again any
+// time a config value (e.g. `bucket`) needs to change for an
+// already-set-up instance (setupPolicyEditor only needs to run once per
+// `which`; its DOM listeners read POLICY_EDITOR_CONFIG live).
+//
+// config:
+// textareaId - id of the JSON <textarea>. Default: which + 'PolicyDocument'.
+// editorBodyId - id of the structured-editor container. Default: which + 'PolicyEditorBody'.
+// addStatementBtnId - id of the "Add statement" button. Default: which + 'PolicyAddStatementBtn'.
+// editorTabBtnId - id of the Editor tab button. Default: which + 'PolicyEditorTabBtn'.
+// jsonTabBtnId - id of the JSON tab button. Default: which + 'PolicyJsonTabBtn'.
+// actionDatalistId - id of the shared action-suggestions <datalist>. Default: 'policyActionSuggestions'.
+// resourceDatalistId - id of the shared resource-suggestions <datalist>. Default: 'policyResourceSuggestions'.
+// principalDatalistId - id of the shared principal-suggestions <datalist>. Default: 'policyPrincipalSuggestions'.
+// requirePrincipal - if true, a new statement seeds Principal with '*'
+// instead of leaving it empty. Bucket policies
+// require a Principal per statement; IAM policies
+// don't. The server remains the source of truth for
+// this rule either way - see
+// policy_engine.ValidateBucketPolicy.
+// bucket - if set, the Resource autocomplete only offers
+// this bucket's ARN and ARN/*, instead of fetching
+// every bucket, and a new statement's Resource is
+// seeded with arn:aws:s3:::<bucket>/*.
+function registerPolicyEditor(which, config) {
+ POLICY_EDITOR_CONFIG[which] = Object.assign({
+ textareaId: which + 'PolicyDocument',
+ editorBodyId: which + 'PolicyEditorBody',
+ addStatementBtnId: which + 'PolicyAddStatementBtn',
+ editorTabBtnId: which + 'PolicyEditorTabBtn',
+ jsonTabBtnId: which + 'PolicyJsonTabBtn',
+ actionDatalistId: 'policyActionSuggestions',
+ resourceDatalistId: 'policyResourceSuggestions',
+ principalDatalistId: 'policyPrincipalSuggestions',
+ requirePrincipal: false,
+ bucket: null
+ }, config || {});
+}
+
+function policyEditorConfig(which) {
+ return POLICY_EDITOR_CONFIG[which] || (registerPolicyEditor(which, {}), POLICY_EDITOR_CONFIG[which]);
+}
+
+ // 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: {} }
+ };
+
+ // Lazily initializes and returns policyEditors[which]. 'create'/'edit'
+ // are pre-populated above, but a page with its own `which` (e.g. the
+ // bucket policy modal) doesn't populate one until its first successful
+ // load - and that load is asynchronous, so the Editor/JSON tabs and
+ // Add-statement button can be reachable before it resolves (nothing in
+ // this file enforces that a page hide them meanwhile). Route reads
+ // through this instead of policyEditors[which] directly wherever that
+ // race is possible, so a click in that window gets a valid empty state
+ // instead of a TypeError on undefined.
+ function policyEditorState(which) {
+ if (!policyEditors[which]) {
+ policyEditors[which] = { version: '2012-10-17', statements: [], otherFields: {} };
+ }
+ return policyEditors[which];
+ }
+
+ 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 policyEditorConfig(which).textareaId;
+ }
+
+ function policyEditorBodyId(which) {
+ return policyEditorConfig(which).editorBodyId;
+ }
+
+ 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 = policyEditorState(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 &mdash; 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) {
+ const cfg = policyEditorConfig(which);
+ let listAttr = '';
+ if (field === 'action') listAttr = ' list="' + cfg.actionDatalistId + '"';
+ else if (field === 'resource') listAttr = ' list="' + cfg.resourceDatalistId + '"';
+ else if (field === 'principal') listAttr = ' list="' + cfg.principalDatalistId + '"';
+ 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 activatePolicyTab(idKey, which) {
+ const btn = document.getElementById(policyEditorConfig(which)[idKey]);
+ if (btn) bootstrap.Tab.getOrCreateInstance(btn).show();
+ }
+
+ // Populates the editor for `which` from whatever is currently in its
+ // JSON textarea (typically right after a GET fills the textarea) and
+ // switches to whichever tab can actually show the result.
+ //
+ // Unlike commitPolicyTextareaToEditor - which assumes a tab is already
+ // showing and leaves it in place on failure so a Save can't silently
+ // clobber it - this function has no "current tab" to defer to: it is
+ // the thing that establishes one. So on a document the structured
+ // editor can't represent (invalid JSON, or valid JSON
+ // policyDocToEditorState rejects), it marks the state `unparsed` and
+ // switches to the JSON tab instead of leaving the Editor tab showing
+ // empty/stale state that a careless Save would serialize over the
+ // real document. Mirrors editPolicy's fallback in policies.templ.
+ function loadPolicyTextareaIntoEditor(which) {
+ const text = document.getElementById(policyTextareaId(which)).value;
+ if (!text || !text.trim()) {
+ policyEditors[which] = { version: '2012-10-17', statements: [], otherFields: {} };
+ renderPolicyEditor(which);
+ activatePolicyTab('editorTabBtnId', which);
+ return true;
+ }
+ let doc;
+ try {
+ doc = JSON.parse(text);
+ } catch (e) {
+ policyEditors[which] = { version: '2012-10-17', statements: [], otherFields: {}, unparsed: true };
+ renderPolicyEditor(which);
+ showAlert('Invalid JSON in stored policy: ' + e.message + '. ' + POLICY_JSON_TAB_ONLY_MESSAGE, 'error');
+ activatePolicyTab('jsonTabBtnId', which);
+ return false;
+ }
+ let state;
+ try {
+ state = policyDocToEditorState(doc);
+ } catch (e) {
+ policyEditors[which] = { version: '2012-10-17', statements: [], otherFields: {}, unparsed: true };
+ renderPolicyEditor(which);
+ showAlert(e.message + '. ' + POLICY_JSON_TAB_ONLY_MESSAGE, 'error');
+ activatePolicyTab('jsonTabBtnId', which);
+ return false;
+ }
+ policyEditors[which] = state;
+ renderPolicyEditor(which);
+ activatePolicyTab('editorTabBtnId', which);
+ return true;
+ }
+
+ function addPolicyStatement(which) {
+ if (policyEditorState(which).unparsed) {
+ showAlert(POLICY_JSON_TAB_ONLY_MESSAGE, 'error');
+ return;
+ }
+ const cfg = policyEditorConfig(which);
+ commitPolicyEditorForm(which);
+ policyEditorState(which).statements.push({
+ sid: '', effect: 'Allow', actions: [],
+ resourceMode: 'Resource', resources: cfg.bucket ? ['arn:aws:s3:::' + cfg.bucket + '/*'] : [],
+ principalMode: 'Principal', principalValues: cfg.requirePrincipal ? ['*'] : [], 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(policyEditorConfig(which).jsonTabBtnId);
+ 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 (policyEditorState(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?');
+ }
+
+ // Client-side check for the requirePrincipal config knob: returns an
+ // error message naming the first statement missing a Principal /
+ // NotPrincipal, or null if the document is fine. Purely a fast-feedback
+ // convenience - the server (policy_engine.ValidateBucketPolicy) is the
+ // actual authority on this rule and re-checks it regardless.
+ function validatePolicyEditorDoc(which, doc) {
+ if (!policyEditorConfig(which).requirePrincipal) return null;
+ const statements = (doc && doc.Statement) || [];
+ for (let i = 0; i < statements.length; i++) {
+ const stmt = statements[i] || {};
+ if (stmt.Principal === undefined && stmt.NotPrincipal === undefined) {
+ return 'Statement ' + (i + 1) + ': a Principal (or NotPrincipal) is required.';
+ }
+ }
+ return null;
+ }
+
+ function setupPolicyEditor(which) {
+ const cfg = policyEditorConfig(which);
+ document.getElementById(cfg.addStatementBtnId).addEventListener('click', function() {
+ addPolicyStatement(which);
+ });
+
+ const editorTabBtn = document.getElementById(cfg.editorTabBtnId);
+ const jsonTabBtn = document.getElementById(cfg.jsonTabBtnId);
+
+ jsonTabBtn.addEventListener('show.bs.tab', function(event) {
+ if (policyEditorState(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(which, target);
+ }
+ });
+ body.addEventListener('focusin', function(event) {
+ const target = event.target;
+ if (target.classList.contains('policy-list-item') && target.getAttribute('data-field') === 'resource') {
+ updatePolicyResourceSuggestions(which, 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(which);
+ }
+ });
+ body.addEventListener('focusin', function(event) {
+ const target = event.target;
+ if (target.classList.contains('policy-list-item') && target.getAttribute('data-field') === 'principal') {
+ updatePolicyPrincipalSuggestions(which);
+ }
+ });
+ }
+
+ // ------------------------------------------------------------------
+ // 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(which, inputEl) {
+ const cfg = policyEditorConfig(which);
+ const datalist = document.getElementById(cfg.resourceDatalistId);
+ if (!datalist) return;
+ const state = policyResourcePathState(inputEl.value);
+
+ if (state.stage === 'bucket') {
+ if (cfg.bucket) {
+ // Pinned to one bucket: no need to fetch and offer every
+ // bucket in the cluster, and the user can't be offered an
+ // ARN the server would reject anyway (see
+ // policy_engine.ValidateBucketPolicy).
+ renderPolicyDatalistOptions(datalist, [
+ POLICY_RESOURCE_ARN_PREFIX + cfg.bucket,
+ POLICY_RESOURCE_ARN_PREFIX + cfg.bucket + '/*'
+ ]);
+ return;
+ }
+ 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(which) {
+ const datalist = document.getElementById(policyEditorConfig(which).principalDatalistId);
+ 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, sampleDoc) {
+ const doc = sampleDoc || POLICY_SAMPLE_DOCUMENT;
+ policyEditors[which] = policyDocToEditorState(doc);
+ renderPolicyEditor(which);
+ document.getElementById(policyTextareaId(which)).value = JSON.stringify(doc, null, 2);
+ }
diff --git a/weed/admin/static/js/s3tables.js b/weed/admin/static/js/s3tables.js
index 2ea7d97095..f143a71da8 100644
--- a/weed/admin/static/js/s3tables.js
+++ b/weed/admin/static/js/s3tables.js
@@ -15,6 +15,23 @@ let s3tablesTablePolicyModal = null;
let s3tablesTagsModal = null;
let icebergTableDeleteModal = null;
+// True only once a bucket/table policy GET has actually completed
+// successfully (a genuinely empty policy counts). Guards the Save handlers
+// below: a failed GET must not let a Save serialize the editor's cleared-out
+// placeholder state as a real "Statement: []" document and overwrite
+// whatever is actually stored.
+let s3tablesBucketPolicyLoaded = false;
+let s3tablesTablePolicyLoaded = false;
+
+// Bumped on every bucket/table policy load; a response only gets applied if
+// its captured sequence number still matches. Without this, opening one
+// resource's policy dialog and then another's before the first GET resolves
+// lets the late response overwrite the second resource's textarea/editor
+// state and mark it loaded, so a subsequent Save would push the first
+// resource's policy onto the second resource.
+let s3tablesBucketPolicyRequestSeq = 0;
+let s3tablesTablePolicyRequestSeq = 0;
+
function getCSRFToken() {
const tokenMeta = document.querySelector('meta[name="csrf-token"]');
if (!tokenMeta) {
@@ -40,6 +57,15 @@ function initS3TablesBuckets() {
s3tablesBucketPolicyModal = new bootstrap.Modal(document.getElementById('s3tablesBucketPolicyModal'));
s3tablesTagsModal = new bootstrap.Modal(document.getElementById('s3tablesTagsModal'));
+ // Shared visual policy editor (weed/admin/static/js/policy_editor.js),
+ // reused here from the bucket policy admin page. Table bucket policies
+ // aren't validated against policy_engine.PolicyDocument server-side
+ // (see s3tables/permissions.go's separate PolicyDocument type), so no
+ // requirePrincipal/bucket config is set - the editor just gives a
+ // structured view over the same JSON the JSON tab holds.
+ registerPolicyEditor('s3tablesBucket', { textareaId: 's3tablesBucketPolicyText' });
+ setupPolicyEditor('s3tablesBucket');
+
const ownerSelect = document.getElementById('s3tablesBucketOwner');
if (ownerSelect) {
document.getElementById('createS3TablesBucketModal').addEventListener('show.bs.modal', async function () {
@@ -179,6 +205,11 @@ function initS3TablesBuckets() {
if (policyForm) {
policyForm.addEventListener('submit', async function (e) {
e.preventDefault();
+ if (!s3tablesBucketPolicyLoaded) {
+ alert('The current policy has not finished loading. Close and reopen this dialog before saving.');
+ return;
+ }
+ if (!commitPolicyActiveTab('s3tablesBucket')) return;
const bucketArn = document.getElementById('s3tablesBucketPolicyArn').value;
const policy = document.getElementById('s3tablesBucketPolicyText').value.trim();
if (!policy) {
@@ -227,6 +258,9 @@ function initS3TablesTables() {
s3tablesTablePolicyModal = new bootstrap.Modal(document.getElementById('s3tablesTablePolicyModal'));
s3tablesTagsModal = new bootstrap.Modal(document.getElementById('s3tablesTagsModal'));
+ registerPolicyEditor('s3tablesTable', { textareaId: 's3tablesTablePolicyText' });
+ setupPolicyEditor('s3tablesTable');
+
const dataContainer = document.getElementById('s3tables-tables-content');
const dataBucketArn = dataContainer.dataset.bucketArn || '';
const dataNamespace = dataContainer.dataset.namespace || '';
@@ -314,6 +348,11 @@ function initS3TablesTables() {
if (policyForm) {
policyForm.addEventListener('submit', async function (e) {
e.preventDefault();
+ if (!s3tablesTablePolicyLoaded) {
+ alert('The current policy has not finished loading. Close and reopen this dialog before saving.');
+ return;
+ }
+ if (!commitPolicyActiveTab('s3tablesTable')) return;
const policy = document.getElementById('s3tablesTablePolicyText').value.trim();
if (!policy) {
alert('Policy JSON is required');
@@ -581,22 +620,51 @@ async function deleteS3TablesBucket() {
}
async function loadS3TablesBucketPolicy(bucketArn) {
+ const requestSeq = ++s3tablesBucketPolicyRequestSeq;
document.getElementById('s3tablesBucketPolicyText').value = '';
- if (!bucketArn) return;
- try {
- const response = await fetch(s3tBasePath(`/api/s3tables/bucket-policy?bucket=${encodeURIComponent(bucketArn)}`));
- const data = await response.json();
- if (response.ok && data.policy) {
- document.getElementById('s3tablesBucketPolicyText').value = data.policy;
+ s3tablesBucketPolicyLoaded = false;
+ // Reset the structured editor immediately too, so a still-open Editor
+ // tab doesn't keep showing the previously loaded resource's statements
+ // while this fetch is in flight.
+ loadPolicyTextareaIntoEditor('s3tablesBucket');
+ if (bucketArn) {
+ let policyText = '';
+ let loadError = null;
+ try {
+ const response = await fetch(s3tBasePath(`/api/s3tables/bucket-policy?bucket=${encodeURIComponent(bucketArn)}`));
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.error || ('HTTP ' + response.status));
+ }
+ if (data.policy) {
+ policyText = data.policy;
+ }
+ } catch (error) {
+ loadError = error;
}
- } catch (error) {
- console.error('Failed to load bucket policy', error);
+ // A newer load (a different bucket, or this one reopened) has since
+ // superseded this response - don't let it touch the shared textarea,
+ // the editor state, or the loaded flag.
+ if (requestSeq !== s3tablesBucketPolicyRequestSeq) return;
+ if (loadError) {
+ console.error('Failed to load bucket policy', loadError);
+ alert('Failed to load bucket policy: ' + loadError.message + '. Close and reopen this dialog to try again.');
+ return;
+ }
+ document.getElementById('s3tablesBucketPolicyText').value = policyText;
}
+ if (requestSeq !== s3tablesBucketPolicyRequestSeq) return;
+ s3tablesBucketPolicyLoaded = true;
+ loadPolicyTextareaIntoEditor('s3tablesBucket');
}
async function deleteS3TablesBucketPolicy() {
const bucketArn = document.getElementById('s3tablesBucketPolicyArn').value;
if (!bucketArn) return;
+ if (!s3tablesBucketPolicyLoaded) {
+ alert('The current policy has not finished loading. Close and reopen this dialog before deleting.');
+ return;
+ }
try {
const response = await fetch(s3tBasePath(`/api/s3tables/bucket-policy?bucket=${encodeURIComponent(bucketArn)}`), { method: 'DELETE', headers: s3tWriteHeaders() });
const data = await response.json();
@@ -606,6 +674,7 @@ async function deleteS3TablesBucketPolicy() {
}
alert('Policy deleted');
document.getElementById('s3tablesBucketPolicyText').value = '';
+ commitPolicyTextareaToEditor('s3tablesBucket');
} catch (error) {
alert('Failed to delete policy: ' + error.message);
}
@@ -677,21 +746,50 @@ async function deleteIcebergTable() {
}
async function loadS3TablesTablePolicy(bucketArn, namespace, name) {
+ const requestSeq = ++s3tablesTablePolicyRequestSeq;
document.getElementById('s3tablesTablePolicyText').value = '';
- if (!bucketArn || !namespace || !name) return;
- const query = new URLSearchParams({ bucket: bucketArn, namespace: namespace, name: name });
- try {
- const response = await fetch(s3tBasePath(`/api/s3tables/table-policy?${query.toString()}`));
- const data = await response.json();
- if (response.ok && data.policy) {
- document.getElementById('s3tablesTablePolicyText').value = data.policy;
+ s3tablesTablePolicyLoaded = false;
+ // Reset the structured editor immediately too, so a still-open Editor
+ // tab doesn't keep showing the previously loaded resource's statements
+ // while this fetch is in flight.
+ loadPolicyTextareaIntoEditor('s3tablesTable');
+ if (bucketArn && namespace && name) {
+ const query = new URLSearchParams({ bucket: bucketArn, namespace: namespace, name: name });
+ let policyText = '';
+ let loadError = null;
+ try {
+ const response = await fetch(s3tBasePath(`/api/s3tables/table-policy?${query.toString()}`));
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.error || ('HTTP ' + response.status));
+ }
+ if (data.policy) {
+ policyText = data.policy;
+ }
+ } catch (error) {
+ loadError = error;
}
- } catch (error) {
- console.error('Failed to load table policy', error);
+ // A newer load (a different table, or this one reopened) has since
+ // superseded this response - don't let it touch the shared textarea,
+ // the editor state, or the loaded flag.
+ if (requestSeq !== s3tablesTablePolicyRequestSeq) return;
+ if (loadError) {
+ console.error('Failed to load table policy', loadError);
+ alert('Failed to load table policy: ' + loadError.message + '. Close and reopen this dialog to try again.');
+ return;
+ }
+ document.getElementById('s3tablesTablePolicyText').value = policyText;
}
+ if (requestSeq !== s3tablesTablePolicyRequestSeq) return;
+ s3tablesTablePolicyLoaded = true;
+ loadPolicyTextareaIntoEditor('s3tablesTable');
}
async function deleteS3TablesTablePolicy() {
+ if (!s3tablesTablePolicyLoaded) {
+ alert('The current policy has not finished loading. Close and reopen this dialog before deleting.');
+ return;
+ }
const dataContainer = document.getElementById('s3tables-tables-content');
const dataBucketArn = dataContainer.dataset.bucketArn || '';
const dataNamespace = dataContainer.dataset.namespace || '';
@@ -705,6 +803,7 @@ async function deleteS3TablesTablePolicy() {
}
alert('Policy deleted');
document.getElementById('s3tablesTablePolicyText').value = '';
+ commitPolicyTextareaToEditor('s3tablesTable');
} catch (error) {
alert('Failed to delete policy: ' + error.message);
}
diff --git a/weed/admin/static_gz/js/policy_editor.js.gz b/weed/admin/static_gz/js/policy_editor.js.gz
new file mode 100644
index 0000000000..5a7183cc23
Binary files /dev/null and b/weed/admin/static_gz/js/policy_editor.js.gz differ
diff --git a/weed/admin/static_gz/js/s3tables.js.gz b/weed/admin/static_gz/js/s3tables.js.gz
index c97a2aca91..2b5cd7e1fb 100644
Binary files a/weed/admin/static_gz/js/s3tables.js.gz and b/weed/admin/static_gz/js/s3tables.js.gz differ
diff --git a/weed/admin/view/app/policies.templ b/weed/admin/view/app/policies.templ
index ac529054f5..dd85f75c28 100644
--- a/weed/admin/view/app/policies.templ
+++ b/weed/admin/view/app/policies.templ
@@ -198,22 +198,7 @@ templ Policies(data dash.PoliciesData) {
}
</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>
+ @PolicyDatalists()
<!-- Create Policy Modal -->
<div class="modal fade" id="createPolicyModal" tabindex="-1" aria-labelledby="createPolicyModalLabel" aria-hidden="true">
@@ -368,729 +353,18 @@ templ Policies(data dash.PoliciesData) {
// Current policy being viewed/edited
let 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 &mdash; 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 actions
document.addEventListener('DOMContentLoaded', function() {
+ // Register the two editor instances used on this page. Config
+ // overrides here preserve the pre-extraction ids exactly, so this
+ // page's markup did not need to change. This has to run after
+ // DOMContentLoaded (not at the top of this script) because
+ // policy_editor.js - which defines registerPolicyEditor - is
+ // loaded by layout.templ's script bundle at the end of <body>,
+ // i.e. after this page's own content (including this inline
+ // script) has already been parsed and run.
+ registerPolicyEditor('create', { textareaId: 'policyDocument' });
+ registerPolicyEditor('edit', { textareaId: 'editPolicyDocument' });
setupPolicyEditor('create');
setupPolicyEditor('edit');
diff --git a/weed/admin/view/app/policies_templ.go b/weed/admin/view/app/policies_templ.go
index 5b93803b2f..4fce2b4a1d 100644
--- a/weed/admin/view/app/policies_templ.go
+++ b/weed/admin/view/app/policies_templ.go
@@ -193,30 +193,15 @@ 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><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\">")
+ 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>")
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 = PolicyDatalists().Render(ctx, templ_7745c5c3_Buffer)
+ 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 &mdash; 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 ? ' &mdash; ' + 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>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "<!-- 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 // Event listeners for policy actions\n document.addEventListener('DOMContentLoaded', function() {\n // Register the two editor instances used on this page. Config\n // overrides here preserve the pre-extraction ids exactly, so this\n // page's markup did not need to change. This has to run after\n // DOMContentLoaded (not at the top of this script) because\n // policy_editor.js - which defines registerPolicyEditor - is\n // loaded by layout.templ's script bundle at the end of <body>,\n // i.e. after this page's own content (including this inline\n // script) has already been parsed and run.\n registerPolicyEditor('create', { textareaId: 'policyDocument' });\n registerPolicyEditor('edit', { textareaId: 'editPolicyDocument' });\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 ? ' &mdash; ' + 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_datalists.templ b/weed/admin/view/app/policy_datalists.templ
new file mode 100644
index 0000000000..53a9165033
--- /dev/null
+++ b/weed/admin/view/app/policy_datalists.templ
@@ -0,0 +1,28 @@
+package app
+
+// PolicyDatalists renders the three <datalist> elements the shared visual
+// policy editor (weed/admin/static/js/policy_editor.js) attaches its
+// action/resource/principal <input list="..."> suggestions to. Any page
+// embedding that editor must render this once; its ids
+// (policyActionSuggestions, policyResourceSuggestions,
+// policyPrincipalSuggestions) are the registerPolicyEditor defaults, so a
+// page only needs to override them if it renders more than one instance of
+// this component.
+templ PolicyDatalists() {
+ <!-- Datalist of suggested action names, shared by every policy editor on this page -->
+ <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() in policy_editor.js. -->
+ <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() in policy_editor.js. -->
+ <datalist id="policyPrincipalSuggestions"></datalist>
+}
diff --git a/weed/admin/view/app/policy_datalists_templ.go b/weed/admin/view/app/policy_datalists_templ.go
new file mode 100644
index 0000000000..0116f68459
--- /dev/null
+++ b/weed/admin/view/app/policy_datalists_templ.go
@@ -0,0 +1,71 @@
+// Code generated by templ - DO NOT EDIT.
+
+// templ: version: v0.3.1020
+package app
+
+//lint:file-ignore SA4006 This context is only used if a nested component is present.
+
+import "github.com/a-h/templ"
+import templruntime "github.com/a-h/templ/runtime"
+
+// PolicyDatalists renders the three <datalist> elements the shared visual
+// policy editor (weed/admin/static/js/policy_editor.js) attaches its
+// action/resource/principal <input list="..."> suggestions to. Any page
+// embedding that editor must render this once; its ids
+// (policyActionSuggestions, policyResourceSuggestions,
+// policyPrincipalSuggestions) are the registerPolicyEditor defaults, so a
+// page only needs to override them if it renders more than one instance of
+// this component.
+func PolicyDatalists() templ.Component {
+ return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
+ if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
+ return templ_7745c5c3_CtxErr
+ }
+ templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
+ if !templ_7745c5c3_IsBuffer {
+ defer func() {
+ templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err == nil {
+ templ_7745c5c3_Err = templ_7745c5c3_BufErr
+ }
+ }()
+ }
+ ctx = templ.InitializeContext(ctx)
+ templ_7745c5c3_Var1 := templ.GetChildren(ctx)
+ if templ_7745c5c3_Var1 == nil {
+ templ_7745c5c3_Var1 = templ.NopComponent
+ }
+ ctx = templ.ClearChildren(ctx)
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<!-- Datalist of suggested action names, shared by every policy editor on this page --><datalist id=\"policyActionSuggestions\">")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ for _, action := range PolicyActionSuggestions {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "<option value=\"")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var2 string
+ templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.ResolveAttributeValue(action)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policy_datalists.templ`, Line: 15, Col: 25}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "\"></option>")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</datalist><!-- Populated dynamically as the user types in a Resource field: bucket\n\t names first, then subfolders one path segment at a time. See\n\t updatePolicyResourceSuggestions() in policy_editor.js. --><datalist id=\"policyResourceSuggestions\"></datalist><!-- Populated dynamically as the user types/focuses a Principal field:\n\t existing users and IAM roles, fetched once from /api/principals. See\n\t updatePolicyPrincipalSuggestions() in policy_editor.js. --><datalist id=\"policyPrincipalSuggestions\"></datalist>")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ return nil
+ })
+}
+
+var _ = templruntime.GeneratedTemplate
diff --git a/weed/admin/view/app/s3_buckets.templ b/weed/admin/view/app/s3_buckets.templ
index 47714f1bd4..fe124cd3a8 100644
--- a/weed/admin/view/app/s3_buckets.templ
+++ b/weed/admin/view/app/s3_buckets.templ
@@ -151,6 +151,7 @@ templ S3Buckets(data dash.S3BucketsData) {
<th>Versioning</th>
<th>Object Lock</th>
<th>Lifecycle</th>
+ <th>Policy</th>
<th>Actions</th>
</tr>
</thead>
@@ -255,6 +256,21 @@ templ S3Buckets(data dash.S3BucketsData) {
<span class="text-muted">Not configured</span>
}
</td>
+ <td>
+ if bucket.PolicyStatementCount > 0 {
+ <button type="button" class="badge bg-primary border-0 policy-btn"
+ data-bucket-name={bucket.Name}
+ title="View Bucket Policy">
+ if bucket.PolicyStatementCount == 1 {
+ 1 statement
+ } else {
+ {fmt.Sprintf("%d statements", bucket.PolicyStatementCount)}
+ }
+ </button>
+ } else {
+ <span class="text-muted">Not configured</span>
+ }
+ </td>
<td>
<div class="btn-group btn-group-sm" role="group">
<a href={dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name))}
@@ -274,7 +290,13 @@ templ S3Buckets(data dash.S3BucketsData) {
title="Lifecycle Rules">
<i class="fas fa-recycle"></i>
</button>
- <button type="button"
+ <button type="button"
+ class="btn btn-outline-info btn-sm policy-btn"
+ data-bucket-name={bucket.Name}
+ title="Bucket Policy">
+ <i class="fas fa-shield-alt"></i>
+ </button>
+ <button type="button"
class="btn btn-outline-info btn-sm owner-btn"
data-bucket-name={bucket.Name}
data-current-owner={bucket.Owner}
@@ -301,7 +323,7 @@ templ S3Buckets(data dash.S3BucketsData) {
}
if len(data.Buckets) == 0 {
<tr>
- <td colspan="10" class="text-center text-muted py-4">
+ <td colspan="11" class="text-center text-muted py-4">
<i class="fas fa-cube fa-3x mb-3 text-muted"></i>
<div>
<h5>No Object Store buckets found</h5>
@@ -661,6 +683,73 @@ templ S3Buckets(data dash.S3BucketsData) {
</div>
</div>
+ @PolicyDatalists()
+
+ <!-- Bucket Policy Modal -->
+ <div class="modal fade" id="bucketPolicyModal" tabindex="-1" aria-labelledby="bucketPolicyModalLabel" aria-hidden="true">
+ <div class="modal-dialog modal-xl">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title" id="bucketPolicyModalLabel">
+ <i class="fas fa-file-shield me-2"></i>Bucket Policy
+ </h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
+ </div>
+ <div class="modal-body">
+ <div id="bucketPolicyLoading" class="text-center py-4">
+ <div class="spinner-border text-primary" role="status">
+ <span class="visually-hidden">Loading...</span>
+ </div>
+ <div class="mt-2">Loading bucket policy...</div>
+ </div>
+ <div id="bucketPolicyError" class="alert alert-danger" style="display: none;"></div>
+ <div id="bucketPolicyEditorWrapper" style="display: none;">
+ <p class="text-muted small">
+ Every statement must specify a Principal, and every Resource must refer to this bucket.
+ Leave the document empty and click Delete to remove the policy.
+ </p>
+ <ul class="nav nav-tabs" role="tablist">
+ <li class="nav-item" role="presentation">
+ <button class="nav-link active" id="bucketPolicyEditorTabBtn" type="button" data-bs-toggle="tab" data-bs-target="#bucketPolicyEditorTab" role="tab" aria-controls="bucketPolicyEditorTab" aria-selected="true">Editor</button>
+ </li>
+ <li class="nav-item" role="presentation">
+ <button class="nav-link" id="bucketPolicyJsonTabBtn" type="button" data-bs-toggle="tab" data-bs-target="#bucketPolicyJsonTab" role="tab" aria-controls="bucketPolicyJsonTab" aria-selected="false">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="bucketPolicyEditorTab" role="tabpanel" aria-labelledby="bucketPolicyEditorTabBtn">
+ <div id="bucketPolicyEditorBody"></div>
+ <button type="button" class="btn btn-sm btn-outline-secondary" id="bucketPolicyAddStatementBtn">
+ <i class="fas fa-plus me-1"></i>Add statement
+ </button>
+ </div>
+ <div class="tab-pane fade" id="bucketPolicyJsonTab" role="tabpanel" aria-labelledby="bucketPolicyJsonTabBtn">
+ <textarea class="form-control" id="bucketPolicyDocument" rows="15"
+ style="font-family: monospace;" spellcheck="false"
+ placeholder='{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::bucket-name/*"}]}'></textarea>
+ <div class="form-text">Enter the bucket policy document as JSON</div>
+ </div>
+ </div>
+ <div class="mb-3">
+ <button type="button" class="btn btn-outline-info btn-sm" id="bucketPolicyInsertSampleBtn">
+ <i class="fas fa-file-alt me-1"></i>Use Sample Policy
+ </button>
+ </div>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-outline-danger me-auto" id="bucketPolicyDeleteBtn">
+ <i class="fas fa-trash me-1"></i>Delete
+ </button>
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
+ <button type="button" class="btn btn-primary" id="bucketPolicySaveBtn">
+ <i class="fas fa-save me-1"></i>Save
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
<!-- Manage Owner Modal -->
<div class="modal fade" id="manageOwnerModal" tabindex="-1" aria-labelledby="manageOwnerModalLabel" aria-hidden="true">
<div class="modal-dialog">
@@ -716,6 +805,30 @@ templ S3Buckets(data dash.S3BucketsData) {
let detailsModalInstance = null;
let lifecycleModalInstance = null;
let lifecycleRequestSeq = 0;
+ let policyModalInstance = null;
+ let policyRequestSeq = 0;
+ let policyEditorBucket = null;
+ // True only once the bucket-policy GET for the currently open bucket has
+ // actually completed successfully. The Save button lives outside the
+ // (initially hidden) editor wrapper, so it stays clickable while a load
+ // is in flight or has failed; without this guard, Save could commit
+ // whatever the editor happened to hold - a stale previous bucket's
+ // statements, or a freshly-initialized empty state - onto
+ // policyEditorBucket before its own policy ever loaded.
+ let bucketPolicyLoaded = false;
+ // True while a Save (PUT) or Delete (DELETE) request for the bucket
+ // policy is in flight, so a double-click - or Save and Delete fired in
+ // quick succession - can't send two overlapping mutations for the same
+ // bucket. Cleared on failure so the user can retry; left set on success,
+ // since the modal hides and the page reloads shortly after anyway.
+ let bucketPolicyMutationInFlight = false;
+
+ function setBucketPolicyMutationInFlight(inFlight) {
+ bucketPolicyMutationInFlight = inFlight;
+ document.getElementById('bucketPolicySaveBtn').disabled = inFlight;
+ document.getElementById('bucketPolicyDeleteBtn').disabled = inFlight;
+ }
+
let cachedUsers = null;
// Working copy of the lifecycle rules currently shown in the modal.
@@ -797,6 +910,7 @@ templ S3Buckets(data dash.S3BucketsData) {
ownerModalInstance = new bootstrap.Modal(document.getElementById('manageOwnerModal'));
detailsModalInstance = new bootstrap.Modal(document.getElementById('bucketDetailsModal'));
lifecycleModalInstance = new bootstrap.Modal(document.getElementById('bucketLifecycleModal'));
+ policyModalInstance = new bootstrap.Modal(document.getElementById('bucketPolicyModal'));
const quotaCheckbox = document.getElementById('enableQuota');
const quotaSettings = document.getElementById('quotaSettings');
@@ -1248,6 +1362,198 @@ templ S3Buckets(data dash.S3BucketsData) {
alert('Error deleting lifecycle rules: ' + error.message);
});
});
+
+ // Policy buttons: column badge and action button. The visual editor
+ // (weed/admin/static/js/policy_editor.js) is set up once per page
+ // load; registerPolicyEditor is re-called on every open so the
+ // resource-ARN autocomplete and default Principal stay pinned to
+ // whichever bucket is currently open.
+ let bucketPolicyEditorSetUp = false;
+ document.getElementById('bucketPolicyInsertSampleBtn').addEventListener('click', function() {
+ if (!policyEditorBucket) return;
+ insertSamplePolicy('bucket', {
+ Version: '2012-10-17',
+ Statement: [{
+ Effect: 'Allow',
+ Principal: '*',
+ Action: ['s3:GetObject'],
+ Resource: ['arn:aws:s3:::' + policyEditorBucket + '/*']
+ }]
+ });
+ });
+
+ document.querySelectorAll('.policy-btn').forEach(button => {
+ button.addEventListener('click', function() {
+ const bucketName = this.dataset.bucketName;
+ policyEditorBucket = bucketName;
+ bucketPolicyLoaded = false;
+ // Deliberately not resetting bucketPolicyMutationInFlight
+ // here: if a Save/Delete for a previously open bucket is
+ // still in flight, Save/Delete for this bucket must stay
+ // blocked until that request settles (its own completion
+ // handler releases the flag once done, whether or not it's
+ // still the active bucket by then) - otherwise this bucket's
+ // mutation could race the abandoned one.
+ registerPolicyEditor('bucket', { requirePrincipal: true, bucket: bucketName });
+ if (!bucketPolicyEditorSetUp) {
+ setupPolicyEditor('bucket');
+ bucketPolicyEditorSetUp = true;
+ }
+
+ document.getElementById('bucketPolicyModalLabel').innerHTML =
+ '<i class="fas fa-file-shield me-2"></i>Bucket Policy - ' + escapeHtml(bucketName);
+ document.getElementById('bucketPolicyLoading').style.display = '';
+ document.getElementById('bucketPolicyError').style.display = 'none';
+ document.getElementById('bucketPolicyEditorWrapper').style.display = 'none';
+
+ policyModalInstance.show();
+
+ // Drop responses that arrive after another bucket was opened
+ const requestSeq = ++policyRequestSeq;
+ fetch(basePath('/api/s3/buckets/' + bucketName + '/policy'))
+ .then(parseLifecycleResponse)
+ .then(({ ok, data }) => {
+ if (requestSeq !== policyRequestSeq) return;
+ document.getElementById('bucketPolicyLoading').style.display = 'none';
+ if (!ok || data.error) {
+ document.getElementById('bucketPolicyError').textContent =
+ 'Error loading bucket policy: ' + (data.error || 'unknown error');
+ document.getElementById('bucketPolicyError').style.display = '';
+ return;
+ }
+ document.getElementById('bucketPolicyEditorWrapper').style.display = '';
+ document.getElementById('bucketPolicyDocument').value =
+ data.policy ? JSON.stringify(data.policy, null, 2) : '';
+ bucketPolicyLoaded = true;
+ loadPolicyTextareaIntoEditor('bucket');
+ })
+ .catch(error => {
+ if (requestSeq !== policyRequestSeq) return;
+ console.error('Error fetching bucket policy:', error);
+ document.getElementById('bucketPolicyLoading').style.display = 'none';
+ document.getElementById('bucketPolicyError').textContent =
+ 'Error loading bucket policy: ' + error.message;
+ document.getElementById('bucketPolicyError').style.display = '';
+ });
+ });
+ });
+
+ // Save the policy document currently shown (whichever tab is active).
+ document.getElementById('bucketPolicySaveBtn').addEventListener('click', function() {
+ if (!policyEditorBucket) return;
+ if (bucketPolicyMutationInFlight) return;
+ if (!bucketPolicyLoaded) {
+ alert('The current policy has not finished loading. Close and reopen this dialog before saving.');
+ return;
+ }
+
+ // Commit first: if the Editor tab is active, the textarea still
+ // holds whatever was there at load time until this runs, so a
+ // policy entered purely through the structured form (no tab
+ // switch) would otherwise read back as empty here.
+ if (!commitPolicyActiveTab('bucket')) return;
+
+ const raw = document.getElementById('bucketPolicyDocument').value.trim();
+ if (!raw) {
+ alert('Enter a policy document, or use Delete to remove the bucket policy.');
+ return;
+ }
+
+ let policy;
+ try {
+ policy = JSON.parse(document.getElementById('bucketPolicyDocument').value);
+ } catch (e) {
+ alert('Invalid JSON: ' + e.message);
+ return;
+ }
+ const validationError = validatePolicyEditorDoc('bucket', policy);
+ if (validationError) {
+ alert(validationError);
+ return;
+ }
+
+ // Captured now: if the dialog moves on to a different bucket
+ // before this PUT resolves, the completion below must not hide
+ // or reload over whatever that other bucket is now showing.
+ const targetBucket = policyEditorBucket;
+ setBucketPolicyMutationInFlight(true);
+ fetch(basePath('/api/s3/buckets/' + targetBucket + '/policy'), {
+ method: 'PUT',
+ headers: csrfHeaders(),
+ body: JSON.stringify({ policy: policy })
+ })
+ .then(parseLifecycleResponse)
+ .then(({ ok, data }) => {
+ setBucketPolicyMutationInFlight(false);
+ const stillCurrent = targetBucket === policyEditorBucket;
+ if (!ok || data.error) {
+ if (stillCurrent) {
+ alert('Error saving bucket policy: ' + (data.error || 'unknown error'));
+ } else {
+ console.error('Error saving policy for ' + targetBucket + ' (no longer the open bucket): ' + (data.error || 'unknown error'));
+ }
+ return;
+ }
+ if (!stillCurrent) return;
+ if (policyModalInstance) {
+ policyModalInstance.hide();
+ }
+ setTimeout(() => location.reload(), 500);
+ })
+ .catch(error => {
+ setBucketPolicyMutationInFlight(false);
+ console.error('Error:', error);
+ if (targetBucket === policyEditorBucket) {
+ alert('Error saving bucket policy: ' + error.message);
+ }
+ });
+ });
+
+ // Clear the bucket policy entirely.
+ document.getElementById('bucketPolicyDeleteBtn').addEventListener('click', function() {
+ if (!policyEditorBucket) return;
+ if (bucketPolicyMutationInFlight) return;
+ if (!bucketPolicyLoaded) {
+ alert('The current policy has not finished loading. Close and reopen this dialog before deleting.');
+ return;
+ }
+ if (!confirm('Delete the bucket policy for ' + policyEditorBucket + '? This cannot be undone.')) return;
+
+ // Captured now: if the dialog moves on to a different bucket
+ // before this DELETE resolves, the completion below must not
+ // hide or reload over whatever that other bucket is now showing.
+ const targetBucket = policyEditorBucket;
+ setBucketPolicyMutationInFlight(true);
+ fetch(basePath('/api/s3/buckets/' + targetBucket + '/policy'), {
+ method: 'DELETE',
+ headers: csrfHeaders()
+ })
+ .then(parseLifecycleResponse)
+ .then(({ ok, data }) => {
+ setBucketPolicyMutationInFlight(false);
+ const stillCurrent = targetBucket === policyEditorBucket;
+ if (!ok || data.error) {
+ if (stillCurrent) {
+ alert('Error deleting bucket policy: ' + (data.error || 'unknown error'));
+ } else {
+ console.error('Error deleting policy for ' + targetBucket + ' (no longer the open bucket): ' + (data.error || 'unknown error'));
+ }
+ return;
+ }
+ if (!stillCurrent) return;
+ if (policyModalInstance) {
+ policyModalInstance.hide();
+ }
+ setTimeout(() => location.reload(), 500);
+ })
+ .catch(error => {
+ setBucketPolicyMutationInFlight(false);
+ console.error('Error:', error);
+ if (targetBucket === policyEditorBucket) {
+ alert('Error deleting bucket policy: ' + error.message);
+ }
+ });
+ });
});
function deleteBucket() {
@@ -1321,6 +1627,12 @@ function displayBucketDetails(data) {
objectLockHtml = '<span class="badge bg-warning"><i class="fas fa-lock me-1"></i>Enabled</span>' + details;
}
+ let policyHtml = '<span class="text-muted">Not configured</span>';
+ if (bucket.policy_statement_count > 0) {
+ const label = bucket.policy_statement_count === 1 ? '1 statement' : bucket.policy_statement_count + ' statements';
+ policyHtml = '<span class="badge bg-primary">' + label + '<\/span>';
+ }
+
const rows = [
'<div class="row">',
'<div class="col-md-6">',
@@ -1341,6 +1653,7 @@ function displayBucketDetails(data) {
'<tr><td><strong>Quota:</strong></td><td>' + quotaHtml + '<\/td><\/tr>',
'<tr><td><strong>Versioning:</strong></td><td>' + versioningHtml + '<\/td><\/tr>',
'<tr><td><strong>Object Lock:</strong></td><td>' + objectLockHtml + '<\/td><\/tr>',
+ '<tr><td><strong>Policy:</strong></td><td>' + policyHtml + '<\/td><\/tr>',
'<\/table>',
'<\/div>',
'<\/div>'
diff --git a/weed/admin/view/app/s3_buckets_templ.go b/weed/admin/view/app/s3_buckets_templ.go
index 98a47a1dcd..64c1ee16a5 100644
--- a/weed/admin/view/app/s3_buckets_templ.go
+++ b/weed/admin/view/app/s3_buckets_templ.go
@@ -1,6 +1,6 @@
// Code generated by templ - DO NOT EDIT.
-// templ: version: v0.3.1001
+// templ: version: v0.3.1020
package app
//lint:file-ignore SA4006 This context is only used if a nested component is present.
@@ -81,7 +81,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalBuckets))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 42, Col: 73}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 42, Col: 73}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil {
@@ -94,7 +94,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(data.TotalSize))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 62, Col: 64}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 62, Col: 64}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
@@ -107,7 +107,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04:05"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 83, Col: 72}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 83, Col: 72}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
@@ -153,7 +153,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</a></th><th>Quota</th><th>Versioning</th><th>Object Lock</th><th>Lifecycle</th><th>Actions</th></tr></thead> <tbody>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</a></th><th>Quota</th><th>Versioning</th><th>Object Lock</th><th>Lifecycle</th><th>Policy</th><th>Actions</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -165,7 +165,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var5 templ.SafeURL
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 161, Col: 124}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 162, Col: 124}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
@@ -178,7 +178,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 164, Col: 64}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 165, Col: 64}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
@@ -206,7 +206,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 175, Col: 101}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 176, Col: 101}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
@@ -229,7 +229,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.CreatedAt.Format("2006-01-02 15:04"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 181, Col: 92}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 182, Col: 92}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
@@ -242,7 +242,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.LogicalSize))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 183, Col: 85}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 184, Col: 85}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
@@ -260,7 +260,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1fx overhead", float64(bucket.PhysicalSize)/float64(bucket.LogicalSize)))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 186, Col: 144}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 187, Col: 144}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
@@ -278,7 +278,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.PhysicalSize))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 190, Col: 81}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 191, Col: 81}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
if templ_7745c5c3_Err != nil {
@@ -303,11 +303,11 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var13 string
- templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(templ.CSSClasses(templ_7745c5c3_Var12).String())
+ templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.ResolveAttributeValue(templ.CSSClasses(templ_7745c5c3_Var12).String())
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 1, Col: 0}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 1, Col: 0}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var13)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -318,7 +318,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.Quota))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 195, Col: 86}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 196, Col: 86}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil {
@@ -336,7 +336,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1f%% used", float64(bucket.LogicalSize)/float64(bucket.Quota)*100))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 199, Col: 146}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 200, Col: 146}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
if templ_7745c5c3_Err != nil {
@@ -394,7 +394,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.ObjectLockMode)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 229, Col: 82}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 230, Col: 82}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
if templ_7745c5c3_Err != nil {
@@ -407,7 +407,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d days", bucket.ObjectLockDuration))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 229, Col: 138}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 230, Col: 138}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
@@ -433,11 +433,11 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var18 string
- templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
+ templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.Name)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 240, Col: 93}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 241, Col: 93}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var18)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -454,7 +454,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d rules", bucket.LifecycleRuleCount))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 245, Col: 115}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 246, Col: 115}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
@@ -473,7 +473,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d enabled", bucket.LifecycleEnabledCount))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 250, Col: 120}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 251, Col: 120}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
@@ -494,309 +494,378 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "</td><td><div class=\"btn-group btn-group-sm\" role=\"group\"><a href=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var21 templ.SafeURL
- templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
+ if bucket.PolicyStatementCount > 0 {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "<button type=\"button\" class=\"badge bg-primary border-0 policy-btn\" data-bucket-name=\"")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var21 string
+ templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.Name)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 262, Col: 89}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var21)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "\" title=\"View Bucket Policy\">")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ if bucket.PolicyStatementCount == 1 {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "1 statement")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ } else {
+ var templ_7745c5c3_Var22 string
+ templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d statements", bucket.PolicyStatementCount))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 267, Col: 118}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "</button>")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ } else {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "<span class=\"text-muted\">Not configured</span>")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "</td><td><div class=\"btn-group btn-group-sm\" role=\"group\"><a href=\"")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var23 templ.SafeURL
+ templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 276, Col: 128}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 260, Col: 128}
+ return templ_7745c5c3_Err
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "\" class=\"btn btn-outline-success btn-sm\" title=\"Browse Files\"><i class=\"fas fa-folder-open\"></i></a> <button type=\"button\" class=\"btn btn-outline-primary btn-sm view-details-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "\" class=\"btn btn-outline-success btn-sm\" title=\"Browse Files\"><i class=\"fas fa-folder-open\"></i></a> <button type=\"button\" class=\"btn btn-outline-primary btn-sm view-details-btn\" data-bucket-name=\"")
+ var templ_7745c5c3_Var24 string
+ templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.Name)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 283, Col: 89}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var24)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var22 string
- templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "\" title=\"View Details\"><i class=\"fas fa-eye\"></i></button> <button type=\"button\" class=\"btn btn-outline-secondary btn-sm lifecycle-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 267, Col: 89}
+ return templ_7745c5c3_Err
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
+ var templ_7745c5c3_Var25 string
+ templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.Name)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 289, Col: 89}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var25)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "\" title=\"View Details\"><i class=\"fas fa-eye\"></i></button> <button type=\"button\" class=\"btn btn-outline-secondary btn-sm lifecycle-btn\" data-bucket-name=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "\" title=\"Lifecycle Rules\"><i class=\"fas fa-recycle\"></i></button> <button type=\"button\" class=\"btn btn-outline-info btn-sm policy-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var23 string
- templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
+ var templ_7745c5c3_Var26 string
+ templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.Name)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 273, Col: 89}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 295, Col: 89}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var26)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "\" title=\"Lifecycle Rules\"><i class=\"fas fa-recycle\"></i></button> <button type=\"button\" class=\"btn btn-outline-info btn-sm owner-btn\" data-bucket-name=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "\" title=\"Bucket Policy\"><i class=\"fas fa-shield-alt\"></i></button> <button type=\"button\" class=\"btn btn-outline-info btn-sm owner-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var24 string
- templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
+ var templ_7745c5c3_Var27 string
+ templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.Name)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 279, Col: 89}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 301, Col: 89}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var27)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "\" data-current-owner=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "\" data-current-owner=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var25 string
- templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)
+ var templ_7745c5c3_Var28 string
+ templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.Owner)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 280, Col: 92}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 302, Col: 92}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var28)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "\" title=\"Manage Owner\"><i class=\"fas fa-user-edit\"></i></button> <button type=\"button\" class=\"btn btn-outline-warning btn-sm quota-btn\" data-bucket-name=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "\" title=\"Manage Owner\"><i class=\"fas fa-user-edit\"></i></button> <button type=\"button\" class=\"btn btn-outline-warning btn-sm quota-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var26 string
- templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
+ var templ_7745c5c3_Var29 string
+ templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.Name)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 286, Col: 89}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 308, Col: 89}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var29)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "\" data-current-quota=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, "\" data-current-quota=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var27 string
- templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", getQuotaInMB(bucket.Quota)))
+ var templ_7745c5c3_Var30 string
+ templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", getQuotaInMB(bucket.Quota)))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 287, Col: 125}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 309, Col: 125}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var30)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "\" data-quota-enabled=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 74, "\" data-quota-enabled=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var28 string
- templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%t", bucket.QuotaEnabled))
+ var templ_7745c5c3_Var31 string
+ templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%t", bucket.QuotaEnabled))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 288, Col: 118}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 310, Col: 118}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var31)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "\" title=\"Manage Quota\"><i class=\"fas fa-tachometer-alt\"></i></button> <button type=\"button\" class=\"btn btn-outline-danger btn-sm delete-bucket-btn\" data-bucket-name=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 75, "\" title=\"Manage Quota\"><i class=\"fas fa-tachometer-alt\"></i></button> <button type=\"button\" class=\"btn btn-outline-danger btn-sm delete-bucket-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var29 string
- templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
+ var templ_7745c5c3_Var32 string
+ templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.Name)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 294, Col: 89}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 316, Col: 89}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var32)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "\" title=\"Delete Bucket\"><i class=\"fas fa-trash\"></i></button></div></td></tr>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 76, "\" title=\"Delete Bucket\"><i class=\"fas fa-trash\"></i></button></div></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if len(data.Buckets) == 0 {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "<tr><td colspan=\"10\" class=\"text-center text-muted py-4\"><i class=\"fas fa-cube fa-3x mb-3 text-muted\"></i><div><h5>No Object Store buckets found</h5><p>Create your first bucket to get started with S3 storage.</p><button type=\"button\" class=\"btn btn-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#createBucketModal\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></td></tr>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 77, "<tr><td colspan=\"11\" class=\"text-center text-muted py-4\"><i class=\"fas fa-cube fa-3x mb-3 text-muted\"></i><div><h5>No Object Store buckets found</h5><p>Create your first bucket to get started with S3 storage.</p><button type=\"button\" class=\"btn btn-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#createBucketModal\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "</tbody></table></div><!-- Pagination Controls -->")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 78, "</tbody></table></div><!-- Pagination Controls -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.TotalPages > 1 {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "<div class=\"d-flex justify-content-between align-items-center mt-3\"><small class=\"text-muted\">Showing ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "<div class=\"d-flex justify-content-between align-items-center mt-3\"><small class=\"text-muted\">Showing ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var30 string
- templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", (data.CurrentPage-1)*data.PageSize+1))
+ var templ_7745c5c3_Var33 string
+ templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", (data.CurrentPage-1)*data.PageSize+1))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 326, Col: 101}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 348, Col: 101}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, " to ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 80, " to ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var31 string
- templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", minInt(data.CurrentPage*data.PageSize, data.TotalBuckets)))
+ var templ_7745c5c3_Var34 string
+ templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", minInt(data.CurrentPage*data.PageSize, data.TotalBuckets)))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 326, Col: 185}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 348, Col: 185}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 74, " of ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, " of ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var32 string
- templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalBuckets))
+ var templ_7745c5c3_Var35 string
+ templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalBuckets))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 326, Col: 229}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 348, Col: 229}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 75, " buckets</small><nav aria-label=\"Buckets pagination\"><ul class=\"pagination pagination-sm mb-0\"><!-- Previous Button -->")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 82, " buckets</small><nav aria-label=\"Buckets pagination\"><ul class=\"pagination pagination-sm mb-0\"><!-- Previous Button -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage > 1 {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 76, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var33 string
- templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage-1))
+ var templ_7745c5c3_Var36 string
+ templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.CurrentPage-1))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 333, Col: 142}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 355, Col: 142}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var36)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 77, "\"><i class=\"fas fa-chevron-left\"></i></a></li>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 84, "\"><i class=\"fas fa-chevron-left\"></i></a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 78, "<li class=\"page-item disabled\"><span class=\"page-link\"><i class=\"fas fa-chevron-left\"></i></span></li>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "<li class=\"page-item disabled\"><span class=\"page-link\"><i class=\"fas fa-chevron-left\"></i></span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "<!-- Page Numbers -->")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "<!-- Page Numbers -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for i := maxInt(1, data.CurrentPage-2); i <= minInt(data.TotalPages, data.CurrentPage+2); i++ {
if i == data.CurrentPage {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 80, "<li class=\"page-item active\"><span class=\"page-link\">")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, "<li class=\"page-item active\"><span class=\"page-link\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var34 string
- templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
+ var templ_7745c5c3_Var37 string
+ templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 349, Col: 97}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 371, Col: 97}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "</span></li>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, "</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 82, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var35 string
- templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
+ var templ_7745c5c3_Var38 string
+ templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", i))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 353, Col: 129}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 375, Col: 129}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var38)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, "\">")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var36 string
- templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
+ var templ_7745c5c3_Var39 string
+ templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 353, Col: 152}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 375, Col: 152}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 84, "</a></li>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "<!-- Next Button -->")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 92, "<!-- Next Button -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage < data.TotalPages {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var37 string
- templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage+1))
+ var templ_7745c5c3_Var40 string
+ templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.CurrentPage+1))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 361, Col: 142}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 383, Col: 142}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var40)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, "\"><i class=\"fas fa-chevron-right\"></i></a></li>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 94, "\"><i class=\"fas fa-chevron-right\"></i></a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, "<li class=\"page-item disabled\"><span class=\"page-link\"><i class=\"fas fa-chevron-right\"></i></span></li>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 95, "<li class=\"page-item disabled\"><span class=\"page-link\"><i class=\"fas fa-chevron-right\"></i></span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "</ul></nav></div>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 96, "</ul></nav></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, "</div></div></div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 97, "</div></div></div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var41 string
+ templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 408, Col: 81}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var38 string
- templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-warning\"></i>Delete Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><p>Are you sure you want to delete the bucket <strong id=\"deleteBucketName\"></strong>?</p><div class=\"alert alert-warning\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <strong>Warning:</strong> This action cannot be undone. All objects in the bucket will be permanently deleted.</div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-danger\" onclick=\"deleteBucket()\"><i class=\"fas fa-trash me-1\"></i>Delete Bucket</button></div></div></div></div><!-- Manage Quota Modal --><div class=\"modal fade\" id=\"manageQuotaModal\" tabindex=\"-1\" aria-labelledby=\"manageQuotaModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"manageQuotaModalLabel\"><i class=\"fas fa-tachometer-alt me-2\"></i>Manage Bucket Quota</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"quotaForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"quotaBucketName\" readonly></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"quotaEnabled\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"quotaEnabled\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSizeSettings\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSizeMB\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSizeMB\" name=\"quota_size\" placeholder=\"1024\" min=\"0\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnitMB\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnitMB\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket. Set to 0 to remove quota.</div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-warning\"><i class=\"fas fa-save me-1\"></i>Update Quota</button></div></form></div></div></div><!-- Bucket Details Modal --><div class=\"modal fade\" id=\"bucketDetailsModal\" tabindex=\"-1\" aria-labelledby=\"bucketDetailsModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"bucketDetailsModalLabel\"><i class=\"fas fa-cube me-2\"></i>Bucket Details</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"bucketDetailsContent\"><div class=\"text-center py-4\"><div class=\"spinner-border text-primary\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><div class=\"mt-2\">Loading bucket details...</div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><!-- Bucket Lifecycle Modal --><div class=\"modal fade\" id=\"bucketLifecycleModal\" tabindex=\"-1\" aria-labelledby=\"bucketLifecycleModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"bucketLifecycleModalLabel\"><i class=\"fas fa-recycle me-2\"></i>Lifecycle</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"bucketLifecycleContent\"></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-outline-danger me-auto\" id=\"lifecycleDeleteAllBtn\"><i class=\"fas fa-trash me-1\"></i>Delete all rules</button> <button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" id=\"lifecycleSaveAllBtn\"><i class=\"fas fa-save me-1\"></i>Save</button></div></div></div></div>")
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 386, Col: 81}
+ return templ_7745c5c3_Err
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
+ templ_7745c5c3_Err = PolicyDatalists().Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-warning\"></i>Delete Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><p>Are you sure you want to delete the bucket <strong id=\"deleteBucketName\"></strong>?</p><div class=\"alert alert-warning\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <strong>Warning:</strong> This action cannot be undone. All objects in the bucket will be permanently deleted.</div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-danger\" onclick=\"deleteBucket()\"><i class=\"fas fa-trash me-1\"></i>Delete Bucket</button></div></div></div></div><!-- Manage Quota Modal --><div class=\"modal fade\" id=\"manageQuotaModal\" tabindex=\"-1\" aria-labelledby=\"manageQuotaModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"manageQuotaModalLabel\"><i class=\"fas fa-tachometer-alt me-2\"></i>Manage Bucket Quota</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"quotaForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"quotaBucketName\" readonly></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"quotaEnabled\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"quotaEnabled\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSizeSettings\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSizeMB\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSizeMB\" name=\"quota_size\" placeholder=\"1024\" min=\"0\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnitMB\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnitMB\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket. Set to 0 to remove quota.</div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-warning\"><i class=\"fas fa-save me-1\"></i>Update Quota</button></div></form></div></div></div><!-- Bucket Details Modal --><div class=\"modal fade\" id=\"bucketDetailsModal\" tabindex=\"-1\" aria-labelledby=\"bucketDetailsModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"bucketDetailsModalLabel\"><i class=\"fas fa-cube me-2\"></i>Bucket Details</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"bucketDetailsContent\"><div class=\"text-center py-4\"><div class=\"spinner-border text-primary\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><div class=\"mt-2\">Loading bucket details...</div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><!-- Bucket Lifecycle Modal --><div class=\"modal fade\" id=\"bucketLifecycleModal\" tabindex=\"-1\" aria-labelledby=\"bucketLifecycleModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"bucketLifecycleModalLabel\"><i class=\"fas fa-recycle me-2\"></i>Lifecycle</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"bucketLifecycleContent\"></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-outline-danger me-auto\" id=\"lifecycleDeleteAllBtn\"><i class=\"fas fa-trash me-1\"></i>Delete all rules</button> <button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" id=\"lifecycleSaveAllBtn\"><i class=\"fas fa-save me-1\"></i>Save</button></div></div></div></div><!-- Manage Owner Modal --><div class=\"modal fade\" id=\"manageOwnerModal\" tabindex=\"-1\" aria-labelledby=\"manageOwnerModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"manageOwnerModalLabel\"><i class=\"fas fa-user-edit me-2\"></i>Manage Bucket Owner</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"ownerForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"ownerBucketName\" readonly></div><div class=\"mb-3\"><label for=\"bucketOwnerSelect\" class=\"form-label\">Owner</label> <select class=\"form-select\" id=\"bucketOwnerSelect\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically --></select><div class=\"form-text\">Select the S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div id=\"ownerLoadingSpinner\" class=\"text-center py-2\" style=\"display: none;\"><div class=\"spinner-border spinner-border-sm text-primary\" role=\"status\"><span class=\"visually-hidden\">Loading users...</span></div><span class=\"ms-2\">Loading users...</span></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-info\"><i class=\"fas fa-save me-1\"></i>Update Owner</button></div></form></div></div></div><!-- JavaScript for bucket management --><script>\n // Global state (shared between DOMContentLoaded handlers and global functions)\n let deleteModalInstance = null;\n let quotaModalInstance = null;\n let ownerModalInstance = null;\n let detailsModalInstance = null;\n let lifecycleModalInstance = null;\n let lifecycleRequestSeq = 0;\n let cachedUsers = null;\n\n // Working copy of the lifecycle rules currently shown in the modal.\n // Edits (add/edit/delete rule) only mutate this local state; nothing is\n // sent to the server until \"Save\" or \"Delete all rules\" is clicked.\n let lifecycleEditor = { bucket: null, rules: [], editingIndex: null, editingRule: null, rawXml: '', hasTransition: false };\n\n function escapeHtml(v) {\n return String(v ?? '')\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n }\n\n // Shadows admin.js's formatBytes for this page, so it keeps that\n // signature and unit list; the extra guard is for a size the API left\n // out, which the shared one renders as \"NaN undefined\".\n function formatBytes(bytes, decimals = 2) {\n if (!bytes) return '0 Bytes';\n const k = 1024;\n const dm = decimals < 0 ? 0 : decimals;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];\n }\n\n function formatDays(n) {\n return n + (n === 1 ? ' day' : ' days');\n }\n\n // csrfHeaders reads the token the layout stamps into every page\n // (<meta name=\"csrf-token\">) so mutating lifecycle requests pass it the\n // same way the newer admin pages (e.g. s3tables) do.\n function csrfHeaders() {\n const meta = document.querySelector('meta[name=\"csrf-token\"]');\n const token = meta ? (meta.getAttribute('content') || '') : '';\n const headers = { 'Content-Type': 'application/json' };\n if (token) {\n headers['X-CSRF-Token'] = token;\n }\n return headers;\n }\n\n // parseLifecycleResponse reads the body as text before parsing, so a\n // non-JSON response (a proxy's HTML error page, an empty body, plain\n // text from some middleware) surfaces the HTTP status instead of\n // throwing a raw JSON syntax error out of response.json().\n function parseLifecycleResponse(response) {\n return response.text().then(text => {\n let data = {};\n if (text) {\n try {\n data = JSON.parse(text);\n } catch (e) {\n data = { error: response.statusText || ('HTTP ' + response.status) };\n }\n } else if (!response.ok) {\n data = { error: response.statusText || ('HTTP ' + response.status) };\n }\n return { ok: response.ok, data: data };\n });\n }\n\n document.addEventListener('DOMContentLoaded', function() {\n // Add click handlers to pagination links\n document.querySelectorAll('.pagination-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const page = this.getAttribute('data-page');\n goToPage(page);\n });\n });\n\n // Initialize modal instances once (reuse with show/hide)\n deleteModalInstance = new bootstrap.Modal(document.getElementById('deleteBucketModal'));\n quotaModalInstance = new bootstrap.Modal(document.getElementById('manageQuotaModal'));\n ownerModalInstance = new bootstrap.Modal(document.getElementById('manageOwnerModal'));\n detailsModalInstance = new bootstrap.Modal(document.getElementById('bucketDetailsModal'));\n lifecycleModalInstance = new bootstrap.Modal(document.getElementById('bucketLifecycleModal'));\n\n const quotaCheckbox = document.getElementById('enableQuota');\n const quotaSettings = document.getElementById('quotaSettings');\n const versioningCheckbox = document.getElementById('enableVersioning');\n const objectLockCheckbox = document.getElementById('enableObjectLock');\n const objectLockSettings = document.getElementById('objectLockSettings');\n const setDefaultRetentionCheckbox = document.getElementById('setDefaultRetention');\n const defaultRetentionSettings = document.getElementById('defaultRetentionSettings');\n const createBucketForm = document.getElementById('createBucketForm');\n\n // Toggle quota settings\n quotaCheckbox.addEventListener('change', function() {\n quotaSettings.style.display = this.checked ? 'block' : 'none';\n });\n\n // Toggle object lock settings and automatically enable versioning\n objectLockCheckbox.addEventListener('change', function() {\n objectLockSettings.style.display = this.checked ? 'block' : 'none';\n if (this.checked) {\n versioningCheckbox.checked = true;\n versioningCheckbox.disabled = true;\n } else {\n versioningCheckbox.disabled = false;\n // Reset default retention settings when object lock is disabled\n setDefaultRetentionCheckbox.checked = false;\n defaultRetentionSettings.style.display = 'none';\n }\n });\n\n // Toggle default retention settings\n setDefaultRetentionCheckbox.addEventListener('change', function() {\n defaultRetentionSettings.style.display = this.checked ? 'block' : 'none';\n });\n\n // Populate owner dropdown when create bucket modal opens\n document.getElementById('createBucketModal').addEventListener('show.bs.modal', async function() {\n const ownerSelect = document.getElementById('bucketOwner');\n \n // Only fetch if not already populated\n if (ownerSelect.options.length <= 1) {\n try {\n const response = await fetch(basePath('/api/users'));\n const data = await response.json();\n const users = data.users || [];\n \n users.forEach(user => {\n const option = document.createElement('option');\n option.value = user.username;\n option.textContent = user.username;\n ownerSelect.appendChild(option);\n });\n } catch (error) {\n console.error('Error fetching users for owner dropdown:', error);\n // Reset to default state on error - user can still create bucket without owner\n ownerSelect.innerHTML = '<option value=\"\">No owner (admin-only access)</option>';\n ownerSelect.selectedIndex = 0;\n }\n }\n });\n\n // Handle form submission\n createBucketForm.addEventListener('submit', function(e) {\n e.preventDefault();\n \n const formData = new FormData(this);\n const data = {\n name: formData.get('name'),\n owner: formData.get('owner') || '',\n region: formData.get('region') || '',\n quota_size: quotaCheckbox.checked ? parseInt(formData.get('quota_size')) || 0 : 0,\n quota_unit: formData.get('quota_unit') || 'MB',\n quota_enabled: quotaCheckbox.checked,\n versioning_enabled: versioningCheckbox.checked,\n object_lock_enabled: objectLockCheckbox.checked,\n object_lock_mode: formData.get('object_lock_mode') || 'GOVERNANCE',\n set_default_retention: setDefaultRetentionCheckbox.checked,\n object_lock_duration: setDefaultRetentionCheckbox.checked ? parseInt(formData.get('object_lock_duration')) || 30 : 0\n };\n\n // Validate object lock settings\n if (data.object_lock_enabled && data.set_default_retention && data.object_lock_duration <= 0) {\n alert('Please enter a valid retention duration for object lock.');\n return;\n }\n\n fetch(basePath('/api/s3/buckets'), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error creating bucket: ' + data.error);\n } else {\n alert('Bucket created successfully!');\n // Properly close the modal before reloading\n const createModal = bootstrap.Modal.getInstance(document.getElementById('createBucketModal'));\n if (createModal) {\n createModal.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error creating bucket: ' + error.message);\n });\n });\n\n // Handle delete bucket\n const deleteForm = document.getElementById('deleteBucketModal');\n document.querySelectorAll('.delete-bucket-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n document.getElementById('deleteBucketName').textContent = bucketName;\n // Store bucket name on modal element instead of global window property\n deleteForm.dataset.bucketName = bucketName;\n deleteModalInstance.show();\n });\n });\n\n // Handle quota management\n const quotaForm = document.getElementById('quotaForm');\n document.querySelectorAll('.quota-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n const currentQuota = parseInt(this.dataset.currentQuota);\n const quotaEnabled = this.dataset.quotaEnabled === 'true';\n \n document.getElementById('quotaBucketName').value = bucketName;\n document.getElementById('quotaEnabled').checked = quotaEnabled;\n document.getElementById('quotaSizeMB').value = currentQuota;\n \n // Toggle quota size settings\n document.getElementById('quotaSizeSettings').style.display = quotaEnabled ? 'block' : 'none';\n \n // Store bucket name on form element instead of global window property\n quotaForm.dataset.bucketName = bucketName;\n quotaModalInstance.show();\n });\n });\n\n // Add event listener to properly dispose of quota modal when hidden\n document.getElementById('manageQuotaModal').addEventListener('hidden.bs.modal', function() {\n if (quotaModalInstance) {\n quotaModalInstance.dispose();\n quotaModalInstance = null;\n }\n // Force remove any remaining backdrops\n document.querySelectorAll('.modal-backdrop').forEach(backdrop => {\n backdrop.remove();\n });\n // Ensure body classes are removed\n document.body.classList.remove('modal-open');\n document.body.style.removeProperty('padding-right');\n });\n\n // Handle quota form submission\n document.getElementById('quotaForm').addEventListener('submit', function(e) {\n e.preventDefault();\n \n const bucketName = this.dataset.bucketName;\n if (!bucketName) return;\n\n const formData = new FormData(this);\n const enabled = document.getElementById('quotaEnabled').checked;\n const data = {\n quota_size: enabled ? parseInt(formData.get('quota_size')) || 0 : 0,\n quota_unit: formData.get('quota_unit') || 'MB',\n quota_enabled: enabled\n };\n\n fetch(basePath(`/api/s3/buckets/${bucketName}/quota`), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error updating quota: ' + data.error);\n } else {\n alert('Quota updated successfully!');\n // Properly close the modal before reloading\n if (quotaModalInstance) {\n quotaModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error updating quota: ' + error.message);\n });\n });\n\n // Handle quota enabled checkbox\n document.getElementById('quotaEnabled').addEventListener('change', function() {\n document.getElementById('quotaSizeSettings').style.display = this.checked ? 'block' : 'none';\n });\n\n // Handle owner management\n const ownerForm = document.getElementById('ownerForm');\n document.querySelectorAll('.owner-btn').forEach(button => {\n button.addEventListener('click', async function() {\n const bucketName = this.dataset.bucketName;\n const currentOwner = this.dataset.currentOwner || '';\n \n document.getElementById('ownerBucketName').value = bucketName;\n // Store bucket name on form element instead of global window property\n ownerForm.dataset.bucketName = bucketName;\n \n // Show loading spinner\n document.getElementById('ownerLoadingSpinner').style.display = 'block';\n document.getElementById('bucketOwnerSelect').disabled = true;\n \n ownerModalInstance.show();\n \n // Fetch users if not cached\n try {\n if (!cachedUsers) {\n const response = await fetch(basePath('/api/users'));\n const data = await response.json();\n cachedUsers = data.users || [];\n }\n \n // Populate the select dropdown\n const select = document.getElementById('bucketOwnerSelect');\n select.innerHTML = '<option value=\"\">No owner (admin-only access)</option>';\n \n cachedUsers.forEach(user => {\n const option = document.createElement('option');\n option.value = user.username;\n option.textContent = user.username;\n if (user.username === currentOwner) {\n option.selected = true;\n }\n select.appendChild(option);\n });\n \n select.disabled = false;\n } catch (error) {\n console.error('Error fetching users:', error);\n alert('Error loading users: ' + error.message);\n // Re-enable select and reset to default on error\n const select = document.getElementById('bucketOwnerSelect');\n select.innerHTML = '<option value=\"\">No owner (admin-only access)</option>';\n select.selectedIndex = 0;\n select.disabled = false;\n } finally {\n document.getElementById('ownerLoadingSpinner').style.display = 'none';\n }\n });\n });\n\n // Handle owner form submission\n document.getElementById('ownerForm').addEventListener('submit', function(e) {\n e.preventDefault();\n \n const bucketName = this.dataset.bucketName;\n if (!bucketName) return;\n\n const owner = document.getElementById('bucketOwnerSelect').value;\n const data = { owner: owner };\n\n fetch(basePath(`/api/s3/buckets/${bucketName}/owner`), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error updating owner: ' + data.error);\n } else {\n alert('Bucket owner updated successfully!');\n // Properly close the modal before reloading\n if (ownerModalInstance) {\n ownerModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error updating owner: ' + error.message);\n });\n });\n\n // Handle view details button\n document.querySelectorAll('.view-details-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n \n // Update modal title\n document.getElementById('bucketDetailsModalLabel').innerHTML = \n '<i class=\"fas fa-cube me-2\"></i>Bucket Details - ' + bucketName;\n \n // Show loading spinner\n document.getElementById('bucketDetailsContent').innerHTML = \n '<div class=\"text-center py-4\">' +\n '<div class=\"spinner-border text-primary\" role=\"status\">' +\n '<span class=\"visually-hidden\">Loading...</span>' +\n '<\\\\/div>' +\n '<div class=\"mt-2\">Loading bucket details...</div>' +\n '<\\\\/div>';\n \n detailsModalInstance.show();\n \n // Fetch bucket details\n fetch(basePath('/api/s3/buckets/' + bucketName))\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n document.getElementById('bucketDetailsContent').innerHTML = \n '<div class=\"alert alert-danger\">' +\n '<i class=\"fas fa-exclamation-triangle me-2\"></i>' +\n 'Error loading bucket details: ' + data.error +\n '<\\\\/div>';\n } else {\n displayBucketDetails(data);\n }\n })\n .catch(error => {\n console.error('Error fetching bucket details:', error);\n document.getElementById('bucketDetailsContent').innerHTML = \n '<div class=\"alert alert-danger\">' +\n '<i class=\"fas fa-exclamation-triangle me-2\"></i>' +\n 'Error loading bucket details: ' + error.message +\n '<\\\\/div>';\n });\n });\n });\n\n // Lifecycle buttons: column badge and action button\n document.querySelectorAll('.lifecycle-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n\n // Reset the working copy until the GET below repopulates it,\n // so Save/Delete-all can't act on the previous bucket's rules.\n lifecycleEditor = { bucket: null, rules: [], editingIndex: null, editingRule: null, rawXml: '', hasTransition: false };\n\n document.getElementById('bucketLifecycleModalLabel').innerHTML =\n '<i class=\"fas fa-recycle me-2\"></i>Lifecycle - ' + bucketName;\n\n document.getElementById('bucketLifecycleContent').innerHTML =\n '<div class=\"text-center py-4\">' +\n '<div class=\"spinner-border text-primary\" role=\"status\">' +\n '<span class=\"visually-hidden\">Loading...</span>' +\n '<\\/div>' +\n '<div class=\"mt-2\">Loading lifecycle rules...</div>' +\n '<\\/div>';\n\n lifecycleModalInstance.show();\n\n // Drop responses that arrive after another bucket was opened\n const requestSeq = ++lifecycleRequestSeq;\n fetch(basePath('/api/s3/buckets/' + bucketName + '/lifecycle'))\n .then(parseLifecycleResponse)\n .then(({ ok, data }) => {\n if (requestSeq !== lifecycleRequestSeq) return;\n if (!ok || data.error) {\n document.getElementById('bucketLifecycleContent').innerHTML =\n '<div class=\"alert alert-danger\">' +\n '<i class=\"fas fa-exclamation-triangle me-2\"></i>' +\n 'Error loading lifecycle rules: ' + (data.error || 'unknown error') +\n '<\\/div>';\n } else {\n displayBucketLifecycle(data);\n }\n })\n .catch(error => {\n if (requestSeq !== lifecycleRequestSeq) return;\n console.error('Error fetching bucket lifecycle:', error);\n document.getElementById('bucketLifecycleContent').innerHTML =\n '<div class=\"alert alert-danger\">' +\n '<i class=\"fas fa-exclamation-triangle me-2\"></i>' +\n 'Error loading lifecycle rules: ' + error.message +\n '<\\/div>';\n });\n });\n });\n\n // Save the whole working rule set back to the bucket.\n document.getElementById('lifecycleSaveAllBtn').addEventListener('click', function() {\n if (!lifecycleEditor.bucket) return;\n // Fold in any rule the user is still editing so Save doesn't\n // silently discard it; abort if that form isn't valid yet.\n if (!commitOpenLifecycleRuleForm()) return;\n // An empty list clears the configuration, same as Delete all rules,\n // so it gets the same prompt.\n if (lifecycleEditor.rules.length === 0 &&\n !confirm('No rules left: saving removes the lifecycle configuration for ' + lifecycleEditor.bucket + '. This cannot be undone.')) {\n return;\n }\n\n fetch(basePath('/api/s3/buckets/' + lifecycleEditor.bucket + '/lifecycle'), {\n method: 'PUT',\n headers: csrfHeaders(),\n body: JSON.stringify({ rules: lifecycleEditor.rules })\n })\n .then(parseLifecycleResponse)\n .then(({ ok, data }) => {\n if (!ok || data.error) {\n alert('Error saving lifecycle rules: ' + (data.error || 'unknown error'));\n return;\n }\n if (lifecycleModalInstance) {\n lifecycleModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error saving lifecycle rules: ' + error.message);\n });\n });\n\n // Clear the lifecycle configuration entirely.\n document.getElementById('lifecycleDeleteAllBtn').addEventListener('click', function() {\n if (!lifecycleEditor.bucket) return;\n if (!confirm('Delete all lifecycle rules for ' + lifecycleEditor.bucket + '? This cannot be undone.')) return;\n\n fetch(basePath('/api/s3/buckets/' + lifecycleEditor.bucket + '/lifecycle'), {\n method: 'DELETE',\n headers: csrfHeaders()\n })\n .then(parseLifecycleResponse)\n .then(({ ok, data }) => {\n if (!ok || data.error) {\n alert('Error deleting lifecycle rules: ' + (data.error || 'unknown error'));\n return;\n }\n if (lifecycleModalInstance) {\n lifecycleModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error deleting lifecycle rules: ' + error.message);\n });\n });\n });\n\n function deleteBucket() {\n const bucketName = document.getElementById('deleteBucketModal').dataset.bucketName;\n if (!bucketName) return;\n\n fetch(basePath(`/api/s3/buckets/${bucketName}`), {\n method: 'DELETE'\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error deleting bucket: ' + data.error);\n } else {\n alert('Bucket deleted successfully!');\n // Properly close the modal before reloading\n if (deleteModalInstance) {\n deleteModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error deleting bucket: ' + error.message);\n });\n }\n\nfunction displayBucketDetails(data) {\n const bucket = data.bucket;\n\n function formatDate(dateString) {\n const date = new Date(dateString);\n return date.toLocaleString();\n }\n\n let ownerHtml = '<span class=\"text-muted\">No owner (admin-only)</span>';\n if (bucket.owner) {\n ownerHtml = '<span class=\"badge bg-info\"><i class=\"fas fa-user me-1\"></i>' + escapeHtml(bucket.owner) + '</span>';\n }\n\n let usageHtml = '';\n if (bucket.physical_size > 0 && bucket.logical_size > 0 && bucket.physical_size > bucket.logical_size) {\n const overhead = (bucket.physical_size / bucket.logical_size).toFixed(1);\n usageHtml = '<br><small class=\"text-muted\">' + overhead + 'x overhead<\\/small>';\n }\n\n let quotaHtml = '<span class=\"badge bg-secondary\">Disabled</span>';\n if (bucket.quota_enabled) {\n quotaHtml = '<span class=\"badge bg-success\">' + formatBytes(bucket.quota) + '</span>';\n }\n\n let versioningHtml = '<span class=\"text-muted\">Not configured</span>';\n if (bucket.versioning_status === 'Enabled') {\n versioningHtml = '<span class=\"badge bg-success\"><i class=\"fas fa-check me-1\"></i>Enabled</span>';\n } else if (bucket.versioning_status === 'Suspended') {\n versioningHtml = '<span class=\"badge bg-warning\"><i class=\"fas fa-pause me-1\"></i>Suspended</span>';\n }\n\n let statusHtml = '<span class=\"badge bg-success\">Writable</span>';\n if (bucket.read_only) {\n statusHtml = '<span class=\"badge bg-danger\"><i class=\"fas fa-lock me-1\"></i>Read-only</span>';\n }\n\n let objectLockHtml = '<span class=\"text-muted\">Not configured</span>';\n if (bucket.object_lock_enabled) {\n let details = '';\n if (bucket.object_lock_mode && bucket.object_lock_duration > 0) {\n details = '<br><small class=\"text-muted\">' + escapeHtml(bucket.object_lock_mode) + ' • ' + bucket.object_lock_duration + ' days<\\/small>';\n }\n objectLockHtml = '<span class=\"badge bg-warning\"><i class=\"fas fa-lock me-1\"></i>Enabled</span>' + details;\n }\n\n const rows = [\n '<div class=\"row\">',\n '<div class=\"col-md-6\">',\n '<h6><i class=\"fas fa-info-circle me-2\"></i>Bucket Information</h6>',\n '<table class=\"table table-sm\">',\n '<tr><td><strong>Name:</strong></td><td>' + escapeHtml(bucket.name) + '<\\/td><\\/tr>',\n '<tr><td><strong>Owner:</strong></td><td>' + ownerHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Created:</strong></td><td>' + formatDate(bucket.created_at) + '<\\/td><\\/tr>',\n '<tr><td><strong>Last Modified:</strong></td><td>' + formatDate(bucket.last_modified) + '<\\/td><\\/tr>',\n '<tr><td><strong>Logical Size:</strong></td><td>' + formatBytes(bucket.logical_size) + '<\\/td><\\/tr>',\n '<tr><td><strong>Physical Size:</strong></td><td>' + formatBytes(bucket.physical_size) + usageHtml + '<\\/td><\\/tr>',\n '<\\/table>',\n '<\\/div>',\n '<div class=\"col-md-6\">',\n '<h6><i class=\"fas fa-cogs me-2\"></i>Configuration</h6>',\n '<table class=\"table table-sm\">',\n '<tr><td><strong>Status:</strong></td><td>' + statusHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Quota:</strong></td><td>' + quotaHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Versioning:</strong></td><td>' + versioningHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Object Lock:</strong></td><td>' + objectLockHtml + '<\\/td><\\/tr>',\n '<\\/table>',\n '<\\/div>',\n '<\\/div>'\n ];\n\n document.getElementById('bucketDetailsContent').innerHTML = rows.join('');\n}\n\n// displayBucketLifecycle loads the GET response into the local working copy\n// and renders the editor. Nothing is sent back to the server until Save or\n// Delete all rules is clicked.\nfunction displayBucketLifecycle(data) {\n lifecycleEditor.bucket = data.bucket || lifecycleEditor.bucket;\n lifecycleEditor.rules = (data.rules || []).map(cloneLifecycleRule);\n lifecycleEditor.editingIndex = null;\n lifecycleEditor.editingRule = null;\n lifecycleEditor.rawXml = data.xml || '';\n // SeaweedFS doesn't support Transition rules (PutBucketLifecycleConfiguration\n // rejects them for Enabled rules), and the canonical rule shape the admin\n // edits has no field for one, so a Transition set by another client would\n // silently disappear on the next Save. Warn instead.\n // Matches <Transition> and <NoncurrentVersionTransition> however they are\n // spelled: with attributes, self-closed, or namespace-prefixed.\n lifecycleEditor.hasTransition = /<(\\w+:)?(NoncurrentVersion)?Transition[\\s>\\/]/.test(data.xml || '');\n renderLifecycleEditor();\n}\n\n// normalizeLifecycleStatus maps a stored status onto the two the editor can\n// show. The S3 API stores <Status> unvalidated, and the engine runs a rule\n// only on an exact \"Enabled\", so everything else is Disabled - collapsing it\n// here keeps an odd spelling from leaving both radios unchecked, which would\n// throw out of readLifecycleRuleFromForm and make the modal look dead.\nfunction normalizeLifecycleStatus(status) {\n return status === 'Enabled' ? 'Enabled' : 'Disabled';\n}\n\nfunction cloneLifecycleRule(r) {\n return {\n id: r.id || '',\n status: normalizeLifecycleStatus(r.status),\n prefix: r.prefix || '',\n tags: Object.assign({}, r.tags || {}),\n size_greater_than: r.size_greater_than || null,\n size_less_than: r.size_less_than || null,\n expiration_days: r.expiration_days || null,\n expiration_date: r.expiration_date || '',\n expired_object_delete_marker: !!r.expired_object_delete_marker,\n noncurrent_version_expiration_days: r.noncurrent_version_expiration_days || null,\n newer_noncurrent_versions: r.newer_noncurrent_versions || null,\n abort_multipart_days: r.abort_multipart_days || null,\n };\n}\n\nfunction blankLifecycleRule() {\n return {\n id: '', status: 'Enabled', prefix: '', tags: {},\n size_greater_than: null, size_less_than: null,\n expiration_days: null, expiration_date: '',\n expired_object_delete_marker: false,\n noncurrent_version_expiration_days: null, newer_noncurrent_versions: null,\n abort_multipart_days: null,\n };\n}\n\nfunction describeLifecycleScope(rule) {\n const parts = [];\n if (rule.prefix) {\n parts.push('<code>' + escapeHtml(rule.prefix) + '<\\/code>');\n }\n Object.entries(rule.tags || {}).forEach(([k, v]) => {\n parts.push('<span class=\"badge bg-light text-dark border\">' + escapeHtml(k) + '=' + escapeHtml(v) + '<\\/span>');\n });\n if (rule.size_greater_than) {\n parts.push('size &gt; ' + formatBytes(rule.size_greater_than));\n }\n if (rule.size_less_than) {\n parts.push('size &lt; ' + formatBytes(rule.size_less_than));\n }\n return parts.length ? parts.join(' ') : '<span class=\"text-muted\">Whole bucket<\\/span>';\n}\n\nfunction describeLifecycleActions(rule) {\n const actions = [];\n if (rule.expiration_days) {\n actions.push('Expire after ' + formatDays(rule.expiration_days));\n }\n if (rule.expiration_date) {\n actions.push('Expire on ' + escapeHtml(rule.expiration_date));\n }\n if (rule.expired_object_delete_marker) {\n actions.push('Remove expired object delete markers');\n }\n if (rule.noncurrent_version_expiration_days) {\n let action = 'Expire noncurrent versions after ' + formatDays(rule.noncurrent_version_expiration_days);\n if (rule.newer_noncurrent_versions) {\n action += ', keep ' + rule.newer_noncurrent_versions + ' newest';\n }\n actions.push(action);\n } else if (rule.newer_noncurrent_versions) {\n // Standalone (no expiration_days): the engine still recognizes this\n // as an action that expires noncurrent versions beyond the N newest.\n actions.push('Keep ' + rule.newer_noncurrent_versions + ' newest noncurrent versions');\n }\n if (rule.abort_multipart_days) {\n actions.push('Abort incomplete multipart uploads after ' + formatDays(rule.abort_multipart_days));\n }\n if (actions.length === 0) {\n return '<span class=\"text-muted\">None<\\/span>';\n }\n return actions.join('<br>');\n}\n\nfunction lifecycleRuleRowHtml(rule, idx) {\n const statusHtml = rule.status === 'Enabled'\n ? '<span class=\"badge bg-success\">Enabled<\\/span>'\n : '<span class=\"badge bg-secondary\">' + escapeHtml(rule.status) + '<\\/span>';\n return '<tr>' +\n '<td>' + (rule.id ? escapeHtml(rule.id) : '<span class=\"text-muted\">unnamed<\\/span>') + '<\\/td>' +\n '<td>' + statusHtml + '<\\/td>' +\n '<td>' + describeLifecycleScope(rule) + '<\\/td>' +\n '<td>' + describeLifecycleActions(rule) + '<\\/td>' +\n '<td class=\"text-end text-nowrap\">' +\n '<button type=\"button\" class=\"btn btn-sm btn-outline-secondary lifecycle-edit-rule-btn\" data-index=\"' + idx + '\" title=\"Edit rule\"><i class=\"fas fa-pen\"><\\/i><\\/button> ' +\n '<button type=\"button\" class=\"btn btn-sm btn-outline-danger lifecycle-delete-rule-btn\" data-index=\"' + idx + '\" title=\"Delete rule\"><i class=\"fas fa-trash\"><\\/i><\\/button>' +\n '<\\/td>' +\n '<\\/tr>';\n}\n\nfunction lifecycleRuleFormHtml() {\n const rule = lifecycleEditor.editingRule;\n const tagRowHtml = (k, v) =>\n '<div class=\"input-group input-group-sm mb-1 lifecycle-tag-row\">' +\n '<input type=\"text\" class=\"form-control lifecycle-tag-key\" placeholder=\"Key\" value=\"' + escapeHtml(k) + '\">' +\n '<input type=\"text\" class=\"form-control lifecycle-tag-value\" placeholder=\"Value\" value=\"' + escapeHtml(v) + '\">' +\n '<button type=\"button\" class=\"btn btn-outline-danger lifecycle-remove-tag-btn\"><i class=\"fas fa-times\"><\\/i><\\/button>' +\n '<\\/div>';\n const tagRows = Object.entries(rule.tags || {}).map(([k, v]) => tagRowHtml(k, v)).join('');\n\n return '' +\n '<div class=\"card mb-3\" id=\"lifecycleRuleForm\">' +\n '<div class=\"card-body\">' +\n '<h6 class=\"card-title\">' + (lifecycleEditor.editingIndex === 'new' ? 'Add rule' : 'Edit rule') + '<\\/h6>' +\n\n '<div class=\"row g-2 mb-2\">' +\n '<div class=\"col-md-6\">' +\n '<label class=\"form-label small\">ID (optional)<\\/label>' +\n '<input type=\"text\" class=\"form-control form-control-sm\" id=\"lifecycleRuleId\" value=\"' + escapeHtml(rule.id) + '\">' +\n '<\\/div>' +\n '<div class=\"col-md-6\">' +\n '<label class=\"form-label small d-block\">Status<\\/label>' +\n '<div class=\"form-check form-check-inline\">' +\n '<input class=\"form-check-input\" type=\"radio\" name=\"lifecycleRuleStatus\" id=\"lifecycleStatusEnabled\" value=\"Enabled\"' + (rule.status === 'Enabled' ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleStatusEnabled\">Enabled<\\/label>' +\n '<\\/div>' +\n '<div class=\"form-check form-check-inline\">' +\n '<input class=\"form-check-input\" type=\"radio\" name=\"lifecycleRuleStatus\" id=\"lifecycleStatusDisabled\" value=\"Disabled\"' + (rule.status === 'Disabled' ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleStatusDisabled\">Disabled<\\/label>' +\n '<\\/div>' +\n '<\\/div>' +\n '<\\/div>' +\n\n '<div class=\"mb-2\">' +\n '<label class=\"form-label small\">Prefix<\\/label>' +\n '<input type=\"text\" class=\"form-control form-control-sm\" id=\"lifecycleRulePrefix\" placeholder=\"logs/\" value=\"' + escapeHtml(rule.prefix) + '\">' +\n '<\\/div>' +\n\n '<div class=\"mb-2\">' +\n '<label class=\"form-label small d-block\">Tags<\\/label>' +\n '<div id=\"lifecycleTagRows\">' + tagRows + '<\\/div>' +\n '<button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"lifecycleAddTagBtn\"><i class=\"fas fa-plus me-1\"><\\/i>Add tag<\\/button>' +\n '<\\/div>' +\n\n '<div class=\"row g-2 mb-3\">' +\n '<div class=\"col-md-6\">' +\n '<label class=\"form-label small\">Size greater than (bytes)<\\/label>' +\n '<input type=\"number\" class=\"form-control form-control-sm\" id=\"lifecycleRuleSizeGT\" min=\"0\" step=\"1\" value=\"' + (rule.size_greater_than || '') + '\">' +\n '<\\/div>' +\n '<div class=\"col-md-6\">' +\n '<label class=\"form-label small\">Size less than (bytes)<\\/label>' +\n '<input type=\"number\" class=\"form-control form-control-sm\" id=\"lifecycleRuleSizeLT\" min=\"0\" step=\"1\" value=\"' + (rule.size_less_than || '') + '\">' +\n '<\\/div>' +\n '<\\/div>' +\n\n '<hr>' +\n '<h6 class=\"small text-muted text-uppercase\">Actions<\\/h6>' +\n\n '<div class=\"row g-2 align-items-center mb-2\">' +\n '<div class=\"col-auto\">' +\n '<div class=\"form-check\">' +\n '<input class=\"form-check-input\" type=\"checkbox\" id=\"lifecycleExpireDaysEnabled\"' + (rule.expiration_days ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleExpireDaysEnabled\">Expire after<\\/label>' +\n '<\\/div>' +\n '<\\/div>' +\n '<div class=\"col-auto\">' +\n '<input type=\"number\" class=\"form-control form-control-sm\" id=\"lifecycleExpireDays\" min=\"1\" step=\"1\" style=\"width: 6rem;\" value=\"' + (rule.expiration_days || '') + '\"' + (rule.expiration_days ? '' : ' disabled') + '>' +\n '<\\/div><div class=\"col-auto\">days<\\/div>' +\n '<\\/div>' +\n\n '<div class=\"row g-2 align-items-center mb-2\">' +\n '<div class=\"col-auto\">' +\n '<div class=\"form-check\">' +\n '<input class=\"form-check-input\" type=\"checkbox\" id=\"lifecycleExpireDateEnabled\"' + (rule.expiration_date ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleExpireDateEnabled\">Expire on date<\\/label>' +\n '<\\/div>' +\n '<\\/div>' +\n '<div class=\"col-auto\">' +\n '<input type=\"date\" class=\"form-control form-control-sm\" id=\"lifecycleExpireDate\" value=\"' + escapeHtml(rule.expiration_date) + '\"' + (rule.expiration_date ? '' : ' disabled') + '>' +\n '<\\/div>' +\n '<\\/div>' +\n\n '<div class=\"form-check mb-2\">' +\n '<input class=\"form-check-input\" type=\"checkbox\" id=\"lifecycleDeleteMarker\"' + (rule.expired_object_delete_marker ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleDeleteMarker\">Remove expired object delete markers<\\/label>' +\n '<\\/div>' +\n\n (() => {\n const noncurrentActive = !!(rule.noncurrent_version_expiration_days || rule.newer_noncurrent_versions);\n return '<div class=\"row g-2 align-items-center mb-2\">' +\n '<div class=\"col-auto\">' +\n '<div class=\"form-check\">' +\n '<input class=\"form-check-input\" type=\"checkbox\" id=\"lifecycleNoncurrentEnabled\"' + (noncurrentActive ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleNoncurrentEnabled\">Limit noncurrent versions<\\/label>' +\n '<\\/div>' +\n '<\\/div>' +\n '<div class=\"col-auto\">after<\\/div>' +\n '<div class=\"col-auto\">' +\n '<input type=\"number\" class=\"form-control form-control-sm\" id=\"lifecycleNoncurrentDays\" min=\"1\" step=\"1\" style=\"width: 6rem;\" value=\"' + (rule.noncurrent_version_expiration_days || '') + '\"' + (noncurrentActive ? '' : ' disabled') + '>' +\n '<\\/div><div class=\"col-auto\">days (optional), keep<\\/div>' +\n '<div class=\"col-auto\">' +\n '<input type=\"number\" class=\"form-control form-control-sm\" id=\"lifecycleNoncurrentKeep\" min=\"0\" step=\"1\" style=\"width: 6rem;\" value=\"' + (rule.newer_noncurrent_versions || '') + '\"' + (noncurrentActive ? '' : ' disabled') + '>' +\n '<\\/div><div class=\"col-auto\">newest (optional)<\\/div>' +\n '<\\/div>';\n })() +\n\n '<div class=\"row g-2 align-items-center mb-3\">' +\n '<div class=\"col-auto\">' +\n '<div class=\"form-check\">' +\n '<input class=\"form-check-input\" type=\"checkbox\" id=\"lifecycleAbortMPUEnabled\"' + (rule.abort_multipart_days ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleAbortMPUEnabled\">Abort incomplete multipart uploads after<\\/label>' +\n '<\\/div>' +\n '<\\/div>' +\n '<div class=\"col-auto\">' +\n '<input type=\"number\" class=\"form-control form-control-sm\" id=\"lifecycleAbortMPUDays\" min=\"1\" step=\"1\" style=\"width: 6rem;\" value=\"' + (rule.abort_multipart_days || '') + '\"' + (rule.abort_multipart_days ? '' : ' disabled') + '>' +\n '<\\/div><div class=\"col-auto\">days<\\/div>' +\n '<\\/div>' +\n\n '<div class=\"text-end\">' +\n '<button type=\"button\" class=\"btn btn-sm btn-secondary\" id=\"lifecycleCancelRuleBtn\">Cancel<\\/button> ' +\n '<button type=\"button\" class=\"btn btn-sm btn-primary\" id=\"lifecycleSaveRuleBtn\">Save rule<\\/button>' +\n '<\\/div>' +\n '<\\/div>' +\n '<\\/div>';\n}\n\nfunction renderLifecycleEditor() {\n const container = document.getElementById('bucketLifecycleContent');\n const rowsHtml = lifecycleEditor.rules.map(lifecycleRuleRowHtml).join('') ||\n '<tr><td colspan=\"5\" class=\"text-center text-muted py-3\">No lifecycle rules<\\/td><\\/tr>';\n\n let html = '';\n if (lifecycleEditor.hasTransition) {\n html += '<div class=\"alert alert-warning small\">' +\n '<i class=\"fas fa-triangle-exclamation me-1\"><\\/i>' +\n 'This bucket has a Transition rule set outside the admin (SeaweedFS does not support storage class transitions). Saving from here will drop it.' +\n '<\\/div>';\n }\n\n html += '<div class=\"table-responsive mb-3\">' +\n '<table class=\"table table-sm align-middle\">' +\n '<thead><tr><th>Rule<\\/th><th>Status<\\/th><th>Scope<\\/th><th>Actions<\\/th><th><\\/th><\\/tr><\\/thead>' +\n '<tbody>' + rowsHtml + '<\\/tbody>' +\n '<\\/table>' +\n '<\\/div>' +\n '<button type=\"button\" class=\"btn btn-sm btn-outline-primary mb-3\" id=\"lifecycleAddRuleBtn\">' +\n '<i class=\"fas fa-plus me-1\"><\\/i>Add rule' +\n '<\\/button>';\n\n if (lifecycleEditor.editingIndex !== null) {\n html += lifecycleRuleFormHtml();\n }\n\n if (lifecycleEditor.rawXml) {\n html += '<details class=\"mt-2\">' +\n '<summary class=\"text-muted small\">Raw XML (as currently stored)<\\/summary>' +\n '<pre class=\"bg-light border rounded p-2 mt-2 small mb-0\">' + escapeHtml(lifecycleEditor.rawXml) + '<\\/pre>' +\n '<\\/details>';\n }\n\n container.innerHTML = html;\n bindLifecycleEditorEvents();\n}\n\nfunction bindLifecycleToggle(checkboxId, fieldId, mutuallyExclusiveId) {\n const checkbox = document.getElementById(checkboxId);\n const field = document.getElementById(fieldId);\n if (!checkbox || !field) return;\n checkbox.addEventListener('change', function() {\n field.disabled = !this.checked;\n if (this.checked && mutuallyExclusiveId) {\n const other = document.getElementById(mutuallyExclusiveId);\n if (other && other.checked) {\n other.checked = false;\n other.dispatchEvent(new Event('change'));\n }\n }\n });\n}\n\nfunction bindLifecycleEditorEvents() {\n const addBtn = document.getElementById('lifecycleAddRuleBtn');\n if (addBtn) {\n addBtn.addEventListener('click', function() {\n // Fold in any rule already being edited before switching forms,\n // so an invalid in-progress draft isn't silently discarded.\n if (!commitOpenLifecycleRuleForm()) return;\n lifecycleEditor.editingIndex = 'new';\n lifecycleEditor.editingRule = blankLifecycleRule();\n renderLifecycleEditor();\n });\n }\n\n document.querySelectorAll('.lifecycle-edit-rule-btn').forEach(btn => {\n btn.addEventListener('click', function() {\n const idx = parseInt(this.dataset.index, 10);\n // Same as above: committing never shifts indices (it either\n // pushes a new rule at the end or replaces one in place), so\n // idx captured above is still valid after this call.\n if (!commitOpenLifecycleRuleForm()) return;\n lifecycleEditor.editingIndex = idx;\n lifecycleEditor.editingRule = cloneLifecycleRule(lifecycleEditor.rules[idx]);\n renderLifecycleEditor();\n });\n });\n\n document.querySelectorAll('.lifecycle-delete-rule-btn').forEach(btn => {\n btn.addEventListener('click', function() {\n const idx = parseInt(this.dataset.index, 10);\n // Fold in an open form first, like every other transition does:\n // re-rendering after the splice would otherwise redraw it from the\n // snapshot taken when editing began and lose what was typed.\n if (lifecycleEditor.editingIndex !== null && lifecycleEditor.editingIndex !== idx) {\n if (!commitOpenLifecycleRuleForm()) return;\n }\n lifecycleEditor.rules.splice(idx, 1);\n // Deleting a rule shifts every later index down by one, so an\n // open edit form must follow its rule rather than silently\n // start targeting whatever now sits at its old index.\n if (lifecycleEditor.editingIndex === idx) {\n lifecycleEditor.editingIndex = null;\n lifecycleEditor.editingRule = null;\n } else if (typeof lifecycleEditor.editingIndex === 'number' && lifecycleEditor.editingIndex > idx) {\n lifecycleEditor.editingIndex -= 1;\n }\n renderLifecycleEditor();\n });\n });\n\n const cancelBtn = document.getElementById('lifecycleCancelRuleBtn');\n if (cancelBtn) {\n cancelBtn.addEventListener('click', function() {\n lifecycleEditor.editingIndex = null;\n lifecycleEditor.editingRule = null;\n renderLifecycleEditor();\n });\n }\n\n const addTagBtn = document.getElementById('lifecycleAddTagBtn');\n if (addTagBtn) {\n addTagBtn.addEventListener('click', function() {\n const rows = document.getElementById('lifecycleTagRows');\n const row = document.createElement('div');\n row.className = 'input-group input-group-sm mb-1 lifecycle-tag-row';\n row.innerHTML =\n '<input type=\"text\" class=\"form-control lifecycle-tag-key\" placeholder=\"Key\">' +\n '<input type=\"text\" class=\"form-control lifecycle-tag-value\" placeholder=\"Value\">' +\n '<button type=\"button\" class=\"btn btn-outline-danger lifecycle-remove-tag-btn\"><i class=\"fas fa-times\"><\\/i><\\/button>';\n rows.appendChild(row);\n row.querySelector('.lifecycle-remove-tag-btn').addEventListener('click', function() {\n row.remove();\n });\n });\n }\n\n document.querySelectorAll('.lifecycle-remove-tag-btn').forEach(btn => {\n btn.addEventListener('click', function() {\n this.closest('.lifecycle-tag-row').remove();\n });\n });\n\n bindLifecycleToggle('lifecycleExpireDaysEnabled', 'lifecycleExpireDays', 'lifecycleExpireDateEnabled');\n bindLifecycleToggle('lifecycleExpireDateEnabled', 'lifecycleExpireDate', 'lifecycleExpireDaysEnabled');\n bindLifecycleToggle('lifecycleNoncurrentEnabled', 'lifecycleNoncurrentDays');\n bindLifecycleToggle('lifecycleNoncurrentEnabled', 'lifecycleNoncurrentKeep');\n bindLifecycleToggle('lifecycleAbortMPUEnabled', 'lifecycleAbortMPUDays');\n\n const saveRuleBtn = document.getElementById('lifecycleSaveRuleBtn');\n if (saveRuleBtn) {\n saveRuleBtn.addEventListener('click', saveLifecycleRuleFromForm);\n }\n}\n\n// readLifecycleRuleFromForm builds and validates a rule from the currently\n// open edit form's DOM inputs. Returns { rule: null, error: '...' } when the\n// form doesn't hold a valid rule, without mutating any state.\nfunction readLifecycleRuleFromForm() {\n const id = document.getElementById('lifecycleRuleId').value.trim();\n const status = document.querySelector('input[name=\"lifecycleRuleStatus\"]:checked').value;\n const prefix = document.getElementById('lifecycleRulePrefix').value.trim();\n\n const tags = {};\n document.querySelectorAll('#lifecycleTagRows .lifecycle-tag-row').forEach(row => {\n const key = row.querySelector('.lifecycle-tag-key').value.trim();\n const value = row.querySelector('.lifecycle-tag-value').value.trim();\n if (key) {\n tags[key] = value;\n }\n });\n\n const sizeGT = parseInt(document.getElementById('lifecycleRuleSizeGT').value, 10) || 0;\n const sizeLT = parseInt(document.getElementById('lifecycleRuleSizeLT').value, 10) || 0;\n\n const expireDaysEnabled = document.getElementById('lifecycleExpireDaysEnabled').checked;\n const expireDateEnabled = document.getElementById('lifecycleExpireDateEnabled').checked;\n const expirationDays = expireDaysEnabled ? (parseInt(document.getElementById('lifecycleExpireDays').value, 10) || 0) : 0;\n const expirationDate = expireDateEnabled ? document.getElementById('lifecycleExpireDate').value : '';\n\n const deleteMarker = document.getElementById('lifecycleDeleteMarker').checked;\n\n const noncurrentEnabled = document.getElementById('lifecycleNoncurrentEnabled').checked;\n const noncurrentDays = noncurrentEnabled ? (parseInt(document.getElementById('lifecycleNoncurrentDays').value, 10) || 0) : 0;\n const noncurrentKeep = noncurrentEnabled ? (parseInt(document.getElementById('lifecycleNoncurrentKeep').value, 10) || 0) : 0;\n\n const abortEnabled = document.getElementById('lifecycleAbortMPUEnabled').checked;\n const abortDays = abortEnabled ? (parseInt(document.getElementById('lifecycleAbortMPUDays').value, 10) || 0) : 0;\n\n if (expireDaysEnabled && expirationDays <= 0) {\n return { rule: null, error: 'Enter a valid number of days for expiration.' };\n }\n if (expireDateEnabled && !expirationDate) {\n return { rule: null, error: 'Enter a valid expiration date.' };\n }\n if (noncurrentEnabled && noncurrentDays <= 0 && noncurrentKeep <= 0) {\n return { rule: null, error: 'Enter a number of days and/or a newest-versions-to-keep count for noncurrent version handling.' };\n }\n if (abortEnabled && abortDays <= 0) {\n return { rule: null, error: 'Enter a valid number of days for aborting incomplete multipart uploads.' };\n }\n if (!expireDaysEnabled && !expireDateEnabled && !deleteMarker && !noncurrentEnabled && !abortEnabled) {\n return { rule: null, error: 'Select at least one action for this rule.' };\n }\n // The server rejects this combination too; catching it here names the two\n // fields instead of surfacing a 400 after the whole set is submitted.\n if (deleteMarker && (expireDaysEnabled || expireDateEnabled)) {\n return { rule: null, error: 'Removing expired object delete markers cannot be combined with an expiration.' };\n }\n if (sizeGT > 0 && sizeLT > 0 && sizeGT >= sizeLT) {\n return { rule: null, error: '\"Size greater than\" must be less than \"size less than\".' };\n }\n\n return {\n rule: {\n id: id,\n status: status,\n prefix: prefix,\n tags: tags,\n size_greater_than: sizeGT > 0 ? sizeGT : null,\n size_less_than: sizeLT > 0 ? sizeLT : null,\n expiration_days: expirationDays > 0 ? expirationDays : null,\n expiration_date: expirationDate || '',\n expired_object_delete_marker: deleteMarker,\n noncurrent_version_expiration_days: noncurrentDays > 0 ? noncurrentDays : null,\n newer_noncurrent_versions: noncurrentKeep > 0 ? noncurrentKeep : null,\n abort_multipart_days: abortDays > 0 ? abortDays : null,\n },\n error: null,\n };\n}\n\nfunction saveLifecycleRuleFromForm() {\n const { rule, error } = readLifecycleRuleFromForm();\n if (error) {\n alert(error);\n return;\n }\n\n if (lifecycleEditor.editingIndex === 'new') {\n lifecycleEditor.rules.push(rule);\n } else {\n lifecycleEditor.rules[lifecycleEditor.editingIndex] = rule;\n }\n lifecycleEditor.editingIndex = null;\n lifecycleEditor.editingRule = null;\n renderLifecycleEditor();\n}\n\n// commitOpenLifecycleRuleForm folds an in-progress add/edit form into\n// lifecycleEditor.rules before the whole rule set is sent to the server, so\n// clicking the modal's \"Save\" without first clicking \"Save rule\" doesn't\n// silently drop the open edit. Returns false (and leaves the form open) when\n// the open form doesn't hold a valid rule, so the caller can abort the save.\nfunction commitOpenLifecycleRuleForm() {\n if (lifecycleEditor.editingIndex === null) {\n return true;\n }\n\n const { rule, error } = readLifecycleRuleFromForm();\n if (error) {\n alert(error);\n return false;\n }\n\n if (lifecycleEditor.editingIndex === 'new') {\n lifecycleEditor.rules.push(rule);\n } else {\n lifecycleEditor.rules[lifecycleEditor.editingIndex] = rule;\n }\n lifecycleEditor.editingIndex = null;\n lifecycleEditor.editingRule = null;\n renderLifecycleEditor();\n return true;\n}\n\n function goToPage(page) {\n const url = new URL(window.location);\n url.searchParams.set('page', page);\n window.location.href = url.toString();\n }\n\n function changePageSize() {\n const pageSize = document.getElementById('pageSizeSelect').value;\n const url = new URL(window.location);\n url.searchParams.set('pageSize', pageSize);\n url.searchParams.set('page', '1');\n window.location.href = url.toString();\n }\n\n function sortTable(column) {\n const url = new URL(window.location);\n const currentSort = url.searchParams.get('sortBy');\n const currentOrder = url.searchParams.get('sortOrder') || 'asc';\n\n let newOrder = 'asc';\n if (currentSort === column && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n\n url.searchParams.set('sortBy', column);\n url.searchParams.set('sortOrder', newOrder);\n url.searchParams.set('page', '1');\n window.location.href = url.toString();\n }\n\n function exportBucketList() {\n // RFC 4180 compliant CSV escaping: escape double quotes by doubling them\n function escapeCsvField(value) {\n const str = String(value ?? '');\n if (str.includes(',') || str.includes('\"') || str.includes('\\n') || str.includes('\\r')) {\n return '\"' + str.replace(/\"/g, '\"\"') + '\"';\n }\n return '\"' + str + '\"';\n }\n\n // Fetch all buckets from the API (not just the current page)\n fetch(basePath('/api/s3/buckets'))\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error exporting buckets: ' + data.error);\n return;\n }\n\n const buckets = data.buckets || [];\n const csvContent = \"data:text/csv;charset=utf-8,\" +\n \"Name,Owner,Logical Size,Physical Size,Created,Quota,Versioning,Object Lock\\n\" +\n buckets.map(b => [\n escapeCsvField(b.name),\n escapeCsvField(b.owner),\n escapeCsvField(formatBytes(b.logical_size)),\n escapeCsvField(formatBytes(b.physical_size)),\n escapeCsvField(b.created_at),\n escapeCsvField(b.quota_enabled ? formatBytes(b.quota) : 'No quota'),\n escapeCsvField(b.versioning_status || 'Not configured'),\n escapeCsvField(b.object_lock_enabled ? 'Enabled' : 'Not configured')\n ].join(',')).join(\"\\n\");\n\n const encodedUri = encodeURI(csvContent);\n const link = document.createElement(\"a\");\n link.setAttribute(\"href\", encodedUri);\n link.setAttribute(\"download\", \"buckets.csv\");\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error exporting buckets: ' + error.message);\n });\n }\n </script>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 99, "<!-- Bucket Policy Modal --><div class=\"modal fade\" id=\"bucketPolicyModal\" tabindex=\"-1\" aria-labelledby=\"bucketPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"bucketPolicyModalLabel\"><i class=\"fas fa-file-shield me-2\"></i>Bucket Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"bucketPolicyLoading\" class=\"text-center py-4\"><div class=\"spinner-border text-primary\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><div class=\"mt-2\">Loading bucket policy...</div></div><div id=\"bucketPolicyError\" class=\"alert alert-danger\" style=\"display: none;\"></div><div id=\"bucketPolicyEditorWrapper\" style=\"display: none;\"><p class=\"text-muted small\">Every statement must specify a Principal, and every Resource must refer to this bucket. Leave the document empty and click Delete to remove the policy.</p><ul class=\"nav nav-tabs\" role=\"tablist\"><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link active\" id=\"bucketPolicyEditorTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#bucketPolicyEditorTab\" role=\"tab\" aria-controls=\"bucketPolicyEditorTab\" aria-selected=\"true\">Editor</button></li><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link\" id=\"bucketPolicyJsonTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#bucketPolicyJsonTab\" role=\"tab\" aria-controls=\"bucketPolicyJsonTab\" aria-selected=\"false\">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=\"bucketPolicyEditorTab\" role=\"tabpanel\" aria-labelledby=\"bucketPolicyEditorTabBtn\"><div id=\"bucketPolicyEditorBody\"></div><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"bucketPolicyAddStatementBtn\"><i class=\"fas fa-plus me-1\"></i>Add statement</button></div><div class=\"tab-pane fade\" id=\"bucketPolicyJsonTab\" role=\"tabpanel\" aria-labelledby=\"bucketPolicyJsonTabBtn\"><textarea class=\"form-control\" id=\"bucketPolicyDocument\" rows=\"15\" style=\"font-family: monospace;\" spellcheck=\"false\" placeholder='{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::bucket-name/*\"}]}'></textarea><div class=\"form-text\">Enter the bucket policy document as JSON</div></div></div><div class=\"mb-3\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" id=\"bucketPolicyInsertSampleBtn\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-outline-danger me-auto\" id=\"bucketPolicyDeleteBtn\"><i class=\"fas fa-trash me-1\"></i>Delete</button> <button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" id=\"bucketPolicySaveBtn\"><i class=\"fas fa-save me-1\"></i>Save</button></div></div></div></div><!-- Manage Owner Modal --><div class=\"modal fade\" id=\"manageOwnerModal\" tabindex=\"-1\" aria-labelledby=\"manageOwnerModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"manageOwnerModalLabel\"><i class=\"fas fa-user-edit me-2\"></i>Manage Bucket Owner</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"ownerForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"ownerBucketName\" readonly></div><div class=\"mb-3\"><label for=\"bucketOwnerSelect\" class=\"form-label\">Owner</label> <select class=\"form-select\" id=\"bucketOwnerSelect\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically --></select><div class=\"form-text\">Select the S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div id=\"ownerLoadingSpinner\" class=\"text-center py-2\" style=\"display: none;\"><div class=\"spinner-border spinner-border-sm text-primary\" role=\"status\"><span class=\"visually-hidden\">Loading users...</span></div><span class=\"ms-2\">Loading users...</span></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-info\"><i class=\"fas fa-save me-1\"></i>Update Owner</button></div></form></div></div></div><!-- JavaScript for bucket management --><script>\n // Global state (shared between DOMContentLoaded handlers and global functions)\n let deleteModalInstance = null;\n let quotaModalInstance = null;\n let ownerModalInstance = null;\n let detailsModalInstance = null;\n let lifecycleModalInstance = null;\n let lifecycleRequestSeq = 0;\n let policyModalInstance = null;\n let policyRequestSeq = 0;\n let policyEditorBucket = null;\n // True only once the bucket-policy GET for the currently open bucket has\n // actually completed successfully. The Save button lives outside the\n // (initially hidden) editor wrapper, so it stays clickable while a load\n // is in flight or has failed; without this guard, Save could commit\n // whatever the editor happened to hold - a stale previous bucket's\n // statements, or a freshly-initialized empty state - onto\n // policyEditorBucket before its own policy ever loaded.\n let bucketPolicyLoaded = false;\n // True while a Save (PUT) or Delete (DELETE) request for the bucket\n // policy is in flight, so a double-click - or Save and Delete fired in\n // quick succession - can't send two overlapping mutations for the same\n // bucket. Cleared on failure so the user can retry; left set on success,\n // since the modal hides and the page reloads shortly after anyway.\n let bucketPolicyMutationInFlight = false;\n\n function setBucketPolicyMutationInFlight(inFlight) {\n bucketPolicyMutationInFlight = inFlight;\n document.getElementById('bucketPolicySaveBtn').disabled = inFlight;\n document.getElementById('bucketPolicyDeleteBtn').disabled = inFlight;\n }\n\n let cachedUsers = null;\n\n // Working copy of the lifecycle rules currently shown in the modal.\n // Edits (add/edit/delete rule) only mutate this local state; nothing is\n // sent to the server until \"Save\" or \"Delete all rules\" is clicked.\n let lifecycleEditor = { bucket: null, rules: [], editingIndex: null, editingRule: null, rawXml: '', hasTransition: false };\n\n function escapeHtml(v) {\n return String(v ?? '')\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n }\n\n // Shadows admin.js's formatBytes for this page, so it keeps that\n // signature and unit list; the extra guard is for a size the API left\n // out, which the shared one renders as \"NaN undefined\".\n function formatBytes(bytes, decimals = 2) {\n if (!bytes) return '0 Bytes';\n const k = 1024;\n const dm = decimals < 0 ? 0 : decimals;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];\n }\n\n function formatDays(n) {\n return n + (n === 1 ? ' day' : ' days');\n }\n\n // csrfHeaders reads the token the layout stamps into every page\n // (<meta name=\"csrf-token\">) so mutating lifecycle requests pass it the\n // same way the newer admin pages (e.g. s3tables) do.\n function csrfHeaders() {\n const meta = document.querySelector('meta[name=\"csrf-token\"]');\n const token = meta ? (meta.getAttribute('content') || '') : '';\n const headers = { 'Content-Type': 'application/json' };\n if (token) {\n headers['X-CSRF-Token'] = token;\n }\n return headers;\n }\n\n // parseLifecycleResponse reads the body as text before parsing, so a\n // non-JSON response (a proxy's HTML error page, an empty body, plain\n // text from some middleware) surfaces the HTTP status instead of\n // throwing a raw JSON syntax error out of response.json().\n function parseLifecycleResponse(response) {\n return response.text().then(text => {\n let data = {};\n if (text) {\n try {\n data = JSON.parse(text);\n } catch (e) {\n data = { error: response.statusText || ('HTTP ' + response.status) };\n }\n } else if (!response.ok) {\n data = { error: response.statusText || ('HTTP ' + response.status) };\n }\n return { ok: response.ok, data: data };\n });\n }\n\n document.addEventListener('DOMContentLoaded', function() {\n // Add click handlers to pagination links\n document.querySelectorAll('.pagination-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const page = this.getAttribute('data-page');\n goToPage(page);\n });\n });\n\n // Initialize modal instances once (reuse with show/hide)\n deleteModalInstance = new bootstrap.Modal(document.getElementById('deleteBucketModal'));\n quotaModalInstance = new bootstrap.Modal(document.getElementById('manageQuotaModal'));\n ownerModalInstance = new bootstrap.Modal(document.getElementById('manageOwnerModal'));\n detailsModalInstance = new bootstrap.Modal(document.getElementById('bucketDetailsModal'));\n lifecycleModalInstance = new bootstrap.Modal(document.getElementById('bucketLifecycleModal'));\n policyModalInstance = new bootstrap.Modal(document.getElementById('bucketPolicyModal'));\n\n const quotaCheckbox = document.getElementById('enableQuota');\n const quotaSettings = document.getElementById('quotaSettings');\n const versioningCheckbox = document.getElementById('enableVersioning');\n const objectLockCheckbox = document.getElementById('enableObjectLock');\n const objectLockSettings = document.getElementById('objectLockSettings');\n const setDefaultRetentionCheckbox = document.getElementById('setDefaultRetention');\n const defaultRetentionSettings = document.getElementById('defaultRetentionSettings');\n const createBucketForm = document.getElementById('createBucketForm');\n\n // Toggle quota settings\n quotaCheckbox.addEventListener('change', function() {\n quotaSettings.style.display = this.checked ? 'block' : 'none';\n });\n\n // Toggle object lock settings and automatically enable versioning\n objectLockCheckbox.addEventListener('change', function() {\n objectLockSettings.style.display = this.checked ? 'block' : 'none';\n if (this.checked) {\n versioningCheckbox.checked = true;\n versioningCheckbox.disabled = true;\n } else {\n versioningCheckbox.disabled = false;\n // Reset default retention settings when object lock is disabled\n setDefaultRetentionCheckbox.checked = false;\n defaultRetentionSettings.style.display = 'none';\n }\n });\n\n // Toggle default retention settings\n setDefaultRetentionCheckbox.addEventListener('change', function() {\n defaultRetentionSettings.style.display = this.checked ? 'block' : 'none';\n });\n\n // Populate owner dropdown when create bucket modal opens\n document.getElementById('createBucketModal').addEventListener('show.bs.modal', async function() {\n const ownerSelect = document.getElementById('bucketOwner');\n \n // Only fetch if not already populated\n if (ownerSelect.options.length <= 1) {\n try {\n const response = await fetch(basePath('/api/users'));\n const data = await response.json();\n const users = data.users || [];\n \n users.forEach(user => {\n const option = document.createElement('option');\n option.value = user.username;\n option.textContent = user.username;\n ownerSelect.appendChild(option);\n });\n } catch (error) {\n console.error('Error fetching users for owner dropdown:', error);\n // Reset to default state on error - user can still create bucket without owner\n ownerSelect.innerHTML = '<option value=\"\">No owner (admin-only access)</option>';\n ownerSelect.selectedIndex = 0;\n }\n }\n });\n\n // Handle form submission\n createBucketForm.addEventListener('submit', function(e) {\n e.preventDefault();\n \n const formData = new FormData(this);\n const data = {\n name: formData.get('name'),\n owner: formData.get('owner') || '',\n region: formData.get('region') || '',\n quota_size: quotaCheckbox.checked ? parseInt(formData.get('quota_size')) || 0 : 0,\n quota_unit: formData.get('quota_unit') || 'MB',\n quota_enabled: quotaCheckbox.checked,\n versioning_enabled: versioningCheckbox.checked,\n object_lock_enabled: objectLockCheckbox.checked,\n object_lock_mode: formData.get('object_lock_mode') || 'GOVERNANCE',\n set_default_retention: setDefaultRetentionCheckbox.checked,\n object_lock_duration: setDefaultRetentionCheckbox.checked ? parseInt(formData.get('object_lock_duration')) || 30 : 0\n };\n\n // Validate object lock settings\n if (data.object_lock_enabled && data.set_default_retention && data.object_lock_duration <= 0) {\n alert('Please enter a valid retention duration for object lock.');\n return;\n }\n\n fetch(basePath('/api/s3/buckets'), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error creating bucket: ' + data.error);\n } else {\n alert('Bucket created successfully!');\n // Properly close the modal before reloading\n const createModal = bootstrap.Modal.getInstance(document.getElementById('createBucketModal'));\n if (createModal) {\n createModal.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error creating bucket: ' + error.message);\n });\n });\n\n // Handle delete bucket\n const deleteForm = document.getElementById('deleteBucketModal');\n document.querySelectorAll('.delete-bucket-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n document.getElementById('deleteBucketName').textContent = bucketName;\n // Store bucket name on modal element instead of global window property\n deleteForm.dataset.bucketName = bucketName;\n deleteModalInstance.show();\n });\n });\n\n // Handle quota management\n const quotaForm = document.getElementById('quotaForm');\n document.querySelectorAll('.quota-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n const currentQuota = parseInt(this.dataset.currentQuota);\n const quotaEnabled = this.dataset.quotaEnabled === 'true';\n \n document.getElementById('quotaBucketName').value = bucketName;\n document.getElementById('quotaEnabled').checked = quotaEnabled;\n document.getElementById('quotaSizeMB').value = currentQuota;\n \n // Toggle quota size settings\n document.getElementById('quotaSizeSettings').style.display = quotaEnabled ? 'block' : 'none';\n \n // Store bucket name on form element instead of global window property\n quotaForm.dataset.bucketName = bucketName;\n quotaModalInstance.show();\n });\n });\n\n // Add event listener to properly dispose of quota modal when hidden\n document.getElementById('manageQuotaModal').addEventListener('hidden.bs.modal', function() {\n if (quotaModalInstance) {\n quotaModalInstance.dispose();\n quotaModalInstance = null;\n }\n // Force remove any remaining backdrops\n document.querySelectorAll('.modal-backdrop').forEach(backdrop => {\n backdrop.remove();\n });\n // Ensure body classes are removed\n document.body.classList.remove('modal-open');\n document.body.style.removeProperty('padding-right');\n });\n\n // Handle quota form submission\n document.getElementById('quotaForm').addEventListener('submit', function(e) {\n e.preventDefault();\n \n const bucketName = this.dataset.bucketName;\n if (!bucketName) return;\n\n const formData = new FormData(this);\n const enabled = document.getElementById('quotaEnabled').checked;\n const data = {\n quota_size: enabled ? parseInt(formData.get('quota_size')) || 0 : 0,\n quota_unit: formData.get('quota_unit') || 'MB',\n quota_enabled: enabled\n };\n\n fetch(basePath(`/api/s3/buckets/${bucketName}/quota`), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error updating quota: ' + data.error);\n } else {\n alert('Quota updated successfully!');\n // Properly close the modal before reloading\n if (quotaModalInstance) {\n quotaModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error updating quota: ' + error.message);\n });\n });\n\n // Handle quota enabled checkbox\n document.getElementById('quotaEnabled').addEventListener('change', function() {\n document.getElementById('quotaSizeSettings').style.display = this.checked ? 'block' : 'none';\n });\n\n // Handle owner management\n const ownerForm = document.getElementById('ownerForm');\n document.querySelectorAll('.owner-btn').forEach(button => {\n button.addEventListener('click', async function() {\n const bucketName = this.dataset.bucketName;\n const currentOwner = this.dataset.currentOwner || '';\n \n document.getElementById('ownerBucketName').value = bucketName;\n // Store bucket name on form element instead of global window property\n ownerForm.dataset.bucketName = bucketName;\n \n // Show loading spinner\n document.getElementById('ownerLoadingSpinner').style.display = 'block';\n document.getElementById('bucketOwnerSelect').disabled = true;\n \n ownerModalInstance.show();\n \n // Fetch users if not cached\n try {\n if (!cachedUsers) {\n const response = await fetch(basePath('/api/users'));\n const data = await response.json();\n cachedUsers = data.users || [];\n }\n \n // Populate the select dropdown\n const select = document.getElementById('bucketOwnerSelect');\n select.innerHTML = '<option value=\"\">No owner (admin-only access)</option>';\n \n cachedUsers.forEach(user => {\n const option = document.createElement('option');\n option.value = user.username;\n option.textContent = user.username;\n if (user.username === currentOwner) {\n option.selected = true;\n }\n select.appendChild(option);\n });\n \n select.disabled = false;\n } catch (error) {\n console.error('Error fetching users:', error);\n alert('Error loading users: ' + error.message);\n // Re-enable select and reset to default on error\n const select = document.getElementById('bucketOwnerSelect');\n select.innerHTML = '<option value=\"\">No owner (admin-only access)</option>';\n select.selectedIndex = 0;\n select.disabled = false;\n } finally {\n document.getElementById('ownerLoadingSpinner').style.display = 'none';\n }\n });\n });\n\n // Handle owner form submission\n document.getElementById('ownerForm').addEventListener('submit', function(e) {\n e.preventDefault();\n \n const bucketName = this.dataset.bucketName;\n if (!bucketName) return;\n\n const owner = document.getElementById('bucketOwnerSelect').value;\n const data = { owner: owner };\n\n fetch(basePath(`/api/s3/buckets/${bucketName}/owner`), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error updating owner: ' + data.error);\n } else {\n alert('Bucket owner updated successfully!');\n // Properly close the modal before reloading\n if (ownerModalInstance) {\n ownerModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error updating owner: ' + error.message);\n });\n });\n\n // Handle view details button\n document.querySelectorAll('.view-details-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n \n // Update modal title\n document.getElementById('bucketDetailsModalLabel').innerHTML = \n '<i class=\"fas fa-cube me-2\"></i>Bucket Details - ' + bucketName;\n \n // Show loading spinner\n document.getElementById('bucketDetailsContent').innerHTML = \n '<div class=\"text-center py-4\">' +\n '<div class=\"spinner-border text-primary\" role=\"status\">' +\n '<span class=\"visually-hidden\">Loading...</span>' +\n '<\\\\/div>' +\n '<div class=\"mt-2\">Loading bucket details...</div>' +\n '<\\\\/div>';\n \n detailsModalInstance.show();\n \n // Fetch bucket details\n fetch(basePath('/api/s3/buckets/' + bucketName))\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n document.getElementById('bucketDetailsContent').innerHTML = \n '<div class=\"alert alert-danger\">' +\n '<i class=\"fas fa-exclamation-triangle me-2\"></i>' +\n 'Error loading bucket details: ' + data.error +\n '<\\\\/div>';\n } else {\n displayBucketDetails(data);\n }\n })\n .catch(error => {\n console.error('Error fetching bucket details:', error);\n document.getElementById('bucketDetailsContent').innerHTML = \n '<div class=\"alert alert-danger\">' +\n '<i class=\"fas fa-exclamation-triangle me-2\"></i>' +\n 'Error loading bucket details: ' + error.message +\n '<\\\\/div>';\n });\n });\n });\n\n // Lifecycle buttons: column badge and action button\n document.querySelectorAll('.lifecycle-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n\n // Reset the working copy until the GET below repopulates it,\n // so Save/Delete-all can't act on the previous bucket's rules.\n lifecycleEditor = { bucket: null, rules: [], editingIndex: null, editingRule: null, rawXml: '', hasTransition: false };\n\n document.getElementById('bucketLifecycleModalLabel').innerHTML =\n '<i class=\"fas fa-recycle me-2\"></i>Lifecycle - ' + bucketName;\n\n document.getElementById('bucketLifecycleContent').innerHTML =\n '<div class=\"text-center py-4\">' +\n '<div class=\"spinner-border text-primary\" role=\"status\">' +\n '<span class=\"visually-hidden\">Loading...</span>' +\n '<\\/div>' +\n '<div class=\"mt-2\">Loading lifecycle rules...</div>' +\n '<\\/div>';\n\n lifecycleModalInstance.show();\n\n // Drop responses that arrive after another bucket was opened\n const requestSeq = ++lifecycleRequestSeq;\n fetch(basePath('/api/s3/buckets/' + bucketName + '/lifecycle'))\n .then(parseLifecycleResponse)\n .then(({ ok, data }) => {\n if (requestSeq !== lifecycleRequestSeq) return;\n if (!ok || data.error) {\n document.getElementById('bucketLifecycleContent').innerHTML =\n '<div class=\"alert alert-danger\">' +\n '<i class=\"fas fa-exclamation-triangle me-2\"></i>' +\n 'Error loading lifecycle rules: ' + (data.error || 'unknown error') +\n '<\\/div>';\n } else {\n displayBucketLifecycle(data);\n }\n })\n .catch(error => {\n if (requestSeq !== lifecycleRequestSeq) return;\n console.error('Error fetching bucket lifecycle:', error);\n document.getElementById('bucketLifecycleContent').innerHTML =\n '<div class=\"alert alert-danger\">' +\n '<i class=\"fas fa-exclamation-triangle me-2\"></i>' +\n 'Error loading lifecycle rules: ' + error.message +\n '<\\/div>';\n });\n });\n });\n\n // Save the whole working rule set back to the bucket.\n document.getElementById('lifecycleSaveAllBtn').addEventListener('click', function() {\n if (!lifecycleEditor.bucket) return;\n // Fold in any rule the user is still editing so Save doesn't\n // silently discard it; abort if that form isn't valid yet.\n if (!commitOpenLifecycleRuleForm()) return;\n // An empty list clears the configuration, same as Delete all rules,\n // so it gets the same prompt.\n if (lifecycleEditor.rules.length === 0 &&\n !confirm('No rules left: saving removes the lifecycle configuration for ' + lifecycleEditor.bucket + '. This cannot be undone.')) {\n return;\n }\n\n fetch(basePath('/api/s3/buckets/' + lifecycleEditor.bucket + '/lifecycle'), {\n method: 'PUT',\n headers: csrfHeaders(),\n body: JSON.stringify({ rules: lifecycleEditor.rules })\n })\n .then(parseLifecycleResponse)\n .then(({ ok, data }) => {\n if (!ok || data.error) {\n alert('Error saving lifecycle rules: ' + (data.error || 'unknown error'));\n return;\n }\n if (lifecycleModalInstance) {\n lifecycleModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error saving lifecycle rules: ' + error.message);\n });\n });\n\n // Clear the lifecycle configuration entirely.\n document.getElementById('lifecycleDeleteAllBtn').addEventListener('click', function() {\n if (!lifecycleEditor.bucket) return;\n if (!confirm('Delete all lifecycle rules for ' + lifecycleEditor.bucket + '? This cannot be undone.')) return;\n\n fetch(basePath('/api/s3/buckets/' + lifecycleEditor.bucket + '/lifecycle'), {\n method: 'DELETE',\n headers: csrfHeaders()\n })\n .then(parseLifecycleResponse)\n .then(({ ok, data }) => {\n if (!ok || data.error) {\n alert('Error deleting lifecycle rules: ' + (data.error || 'unknown error'));\n return;\n }\n if (lifecycleModalInstance) {\n lifecycleModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error deleting lifecycle rules: ' + error.message);\n });\n });\n\n // Policy buttons: column badge and action button. The visual editor\n // (weed/admin/static/js/policy_editor.js) is set up once per page\n // load; registerPolicyEditor is re-called on every open so the\n // resource-ARN autocomplete and default Principal stay pinned to\n // whichever bucket is currently open.\n let bucketPolicyEditorSetUp = false;\n document.getElementById('bucketPolicyInsertSampleBtn').addEventListener('click', function() {\n if (!policyEditorBucket) return;\n insertSamplePolicy('bucket', {\n Version: '2012-10-17',\n Statement: [{\n Effect: 'Allow',\n Principal: '*',\n Action: ['s3:GetObject'],\n Resource: ['arn:aws:s3:::' + policyEditorBucket + '/*']\n }]\n });\n });\n\n document.querySelectorAll('.policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n policyEditorBucket = bucketName;\n bucketPolicyLoaded = false;\n // Deliberately not resetting bucketPolicyMutationInFlight\n // here: if a Save/Delete for a previously open bucket is\n // still in flight, Save/Delete for this bucket must stay\n // blocked until that request settles (its own completion\n // handler releases the flag once done, whether or not it's\n // still the active bucket by then) - otherwise this bucket's\n // mutation could race the abandoned one.\n registerPolicyEditor('bucket', { requirePrincipal: true, bucket: bucketName });\n if (!bucketPolicyEditorSetUp) {\n setupPolicyEditor('bucket');\n bucketPolicyEditorSetUp = true;\n }\n\n document.getElementById('bucketPolicyModalLabel').innerHTML =\n '<i class=\"fas fa-file-shield me-2\"></i>Bucket Policy - ' + escapeHtml(bucketName);\n document.getElementById('bucketPolicyLoading').style.display = '';\n document.getElementById('bucketPolicyError').style.display = 'none';\n document.getElementById('bucketPolicyEditorWrapper').style.display = 'none';\n\n policyModalInstance.show();\n\n // Drop responses that arrive after another bucket was opened\n const requestSeq = ++policyRequestSeq;\n fetch(basePath('/api/s3/buckets/' + bucketName + '/policy'))\n .then(parseLifecycleResponse)\n .then(({ ok, data }) => {\n if (requestSeq !== policyRequestSeq) return;\n document.getElementById('bucketPolicyLoading').style.display = 'none';\n if (!ok || data.error) {\n document.getElementById('bucketPolicyError').textContent =\n 'Error loading bucket policy: ' + (data.error || 'unknown error');\n document.getElementById('bucketPolicyError').style.display = '';\n return;\n }\n document.getElementById('bucketPolicyEditorWrapper').style.display = '';\n document.getElementById('bucketPolicyDocument').value =\n data.policy ? JSON.stringify(data.policy, null, 2) : '';\n bucketPolicyLoaded = true;\n loadPolicyTextareaIntoEditor('bucket');\n })\n .catch(error => {\n if (requestSeq !== policyRequestSeq) return;\n console.error('Error fetching bucket policy:', error);\n document.getElementById('bucketPolicyLoading').style.display = 'none';\n document.getElementById('bucketPolicyError').textContent =\n 'Error loading bucket policy: ' + error.message;\n document.getElementById('bucketPolicyError').style.display = '';\n });\n });\n });\n\n // Save the policy document currently shown (whichever tab is active).\n document.getElementById('bucketPolicySaveBtn').addEventListener('click', function() {\n if (!policyEditorBucket) return;\n if (bucketPolicyMutationInFlight) return;\n if (!bucketPolicyLoaded) {\n alert('The current policy has not finished loading. Close and reopen this dialog before saving.');\n return;\n }\n\n // Commit first: if the Editor tab is active, the textarea still\n // holds whatever was there at load time until this runs, so a\n // policy entered purely through the structured form (no tab\n // switch) would otherwise read back as empty here.\n if (!commitPolicyActiveTab('bucket')) return;\n\n const raw = document.getElementById('bucketPolicyDocument').value.trim();\n if (!raw) {\n alert('Enter a policy document, or use Delete to remove the bucket policy.');\n return;\n }\n\n let policy;\n try {\n policy = JSON.parse(document.getElementById('bucketPolicyDocument').value);\n } catch (e) {\n alert('Invalid JSON: ' + e.message);\n return;\n }\n const validationError = validatePolicyEditorDoc('bucket', policy);\n if (validationError) {\n alert(validationError);\n return;\n }\n\n // Captured now: if the dialog moves on to a different bucket\n // before this PUT resolves, the completion below must not hide\n // or reload over whatever that other bucket is now showing.\n const targetBucket = policyEditorBucket;\n setBucketPolicyMutationInFlight(true);\n fetch(basePath('/api/s3/buckets/' + targetBucket + '/policy'), {\n method: 'PUT',\n headers: csrfHeaders(),\n body: JSON.stringify({ policy: policy })\n })\n .then(parseLifecycleResponse)\n .then(({ ok, data }) => {\n setBucketPolicyMutationInFlight(false);\n const stillCurrent = targetBucket === policyEditorBucket;\n if (!ok || data.error) {\n if (stillCurrent) {\n alert('Error saving bucket policy: ' + (data.error || 'unknown error'));\n } else {\n console.error('Error saving policy for ' + targetBucket + ' (no longer the open bucket): ' + (data.error || 'unknown error'));\n }\n return;\n }\n if (!stillCurrent) return;\n if (policyModalInstance) {\n policyModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n })\n .catch(error => {\n setBucketPolicyMutationInFlight(false);\n console.error('Error:', error);\n if (targetBucket === policyEditorBucket) {\n alert('Error saving bucket policy: ' + error.message);\n }\n });\n });\n\n // Clear the bucket policy entirely.\n document.getElementById('bucketPolicyDeleteBtn').addEventListener('click', function() {\n if (!policyEditorBucket) return;\n if (bucketPolicyMutationInFlight) return;\n if (!bucketPolicyLoaded) {\n alert('The current policy has not finished loading. Close and reopen this dialog before deleting.');\n return;\n }\n if (!confirm('Delete the bucket policy for ' + policyEditorBucket + '? This cannot be undone.')) return;\n\n // Captured now: if the dialog moves on to a different bucket\n // before this DELETE resolves, the completion below must not\n // hide or reload over whatever that other bucket is now showing.\n const targetBucket = policyEditorBucket;\n setBucketPolicyMutationInFlight(true);\n fetch(basePath('/api/s3/buckets/' + targetBucket + '/policy'), {\n method: 'DELETE',\n headers: csrfHeaders()\n })\n .then(parseLifecycleResponse)\n .then(({ ok, data }) => {\n setBucketPolicyMutationInFlight(false);\n const stillCurrent = targetBucket === policyEditorBucket;\n if (!ok || data.error) {\n if (stillCurrent) {\n alert('Error deleting bucket policy: ' + (data.error || 'unknown error'));\n } else {\n console.error('Error deleting policy for ' + targetBucket + ' (no longer the open bucket): ' + (data.error || 'unknown error'));\n }\n return;\n }\n if (!stillCurrent) return;\n if (policyModalInstance) {\n policyModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n })\n .catch(error => {\n setBucketPolicyMutationInFlight(false);\n console.error('Error:', error);\n if (targetBucket === policyEditorBucket) {\n alert('Error deleting bucket policy: ' + error.message);\n }\n });\n });\n });\n\n function deleteBucket() {\n const bucketName = document.getElementById('deleteBucketModal').dataset.bucketName;\n if (!bucketName) return;\n\n fetch(basePath(`/api/s3/buckets/${bucketName}`), {\n method: 'DELETE'\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error deleting bucket: ' + data.error);\n } else {\n alert('Bucket deleted successfully!');\n // Properly close the modal before reloading\n if (deleteModalInstance) {\n deleteModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error deleting bucket: ' + error.message);\n });\n }\n\nfunction displayBucketDetails(data) {\n const bucket = data.bucket;\n\n function formatDate(dateString) {\n const date = new Date(dateString);\n return date.toLocaleString();\n }\n\n let ownerHtml = '<span class=\"text-muted\">No owner (admin-only)</span>';\n if (bucket.owner) {\n ownerHtml = '<span class=\"badge bg-info\"><i class=\"fas fa-user me-1\"></i>' + escapeHtml(bucket.owner) + '</span>';\n }\n\n let usageHtml = '';\n if (bucket.physical_size > 0 && bucket.logical_size > 0 && bucket.physical_size > bucket.logical_size) {\n const overhead = (bucket.physical_size / bucket.logical_size).toFixed(1);\n usageHtml = '<br><small class=\"text-muted\">' + overhead + 'x overhead<\\/small>';\n }\n\n let quotaHtml = '<span class=\"badge bg-secondary\">Disabled</span>';\n if (bucket.quota_enabled) {\n quotaHtml = '<span class=\"badge bg-success\">' + formatBytes(bucket.quota) + '</span>';\n }\n\n let versioningHtml = '<span class=\"text-muted\">Not configured</span>';\n if (bucket.versioning_status === 'Enabled') {\n versioningHtml = '<span class=\"badge bg-success\"><i class=\"fas fa-check me-1\"></i>Enabled</span>';\n } else if (bucket.versioning_status === 'Suspended') {\n versioningHtml = '<span class=\"badge bg-warning\"><i class=\"fas fa-pause me-1\"></i>Suspended</span>';\n }\n\n let statusHtml = '<span class=\"badge bg-success\">Writable</span>';\n if (bucket.read_only) {\n statusHtml = '<span class=\"badge bg-danger\"><i class=\"fas fa-lock me-1\"></i>Read-only</span>';\n }\n\n let objectLockHtml = '<span class=\"text-muted\">Not configured</span>';\n if (bucket.object_lock_enabled) {\n let details = '';\n if (bucket.object_lock_mode && bucket.object_lock_duration > 0) {\n details = '<br><small class=\"text-muted\">' + escapeHtml(bucket.object_lock_mode) + ' • ' + bucket.object_lock_duration + ' days<\\/small>';\n }\n objectLockHtml = '<span class=\"badge bg-warning\"><i class=\"fas fa-lock me-1\"></i>Enabled</span>' + details;\n }\n\n let policyHtml = '<span class=\"text-muted\">Not configured</span>';\n if (bucket.policy_statement_count > 0) {\n const label = bucket.policy_statement_count === 1 ? '1 statement' : bucket.policy_statement_count + ' statements';\n policyHtml = '<span class=\"badge bg-primary\">' + label + '<\\/span>';\n }\n\n const rows = [\n '<div class=\"row\">',\n '<div class=\"col-md-6\">',\n '<h6><i class=\"fas fa-info-circle me-2\"></i>Bucket Information</h6>',\n '<table class=\"table table-sm\">',\n '<tr><td><strong>Name:</strong></td><td>' + escapeHtml(bucket.name) + '<\\/td><\\/tr>',\n '<tr><td><strong>Owner:</strong></td><td>' + ownerHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Created:</strong></td><td>' + formatDate(bucket.created_at) + '<\\/td><\\/tr>',\n '<tr><td><strong>Last Modified:</strong></td><td>' + formatDate(bucket.last_modified) + '<\\/td><\\/tr>',\n '<tr><td><strong>Logical Size:</strong></td><td>' + formatBytes(bucket.logical_size) + '<\\/td><\\/tr>',\n '<tr><td><strong>Physical Size:</strong></td><td>' + formatBytes(bucket.physical_size) + usageHtml + '<\\/td><\\/tr>',\n '<\\/table>',\n '<\\/div>',\n '<div class=\"col-md-6\">',\n '<h6><i class=\"fas fa-cogs me-2\"></i>Configuration</h6>',\n '<table class=\"table table-sm\">',\n '<tr><td><strong>Status:</strong></td><td>' + statusHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Quota:</strong></td><td>' + quotaHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Versioning:</strong></td><td>' + versioningHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Object Lock:</strong></td><td>' + objectLockHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Policy:</strong></td><td>' + policyHtml + '<\\/td><\\/tr>',\n '<\\/table>',\n '<\\/div>',\n '<\\/div>'\n ];\n\n document.getElementById('bucketDetailsContent').innerHTML = rows.join('');\n}\n\n// displayBucketLifecycle loads the GET response into the local working copy\n// and renders the editor. Nothing is sent back to the server until Save or\n// Delete all rules is clicked.\nfunction displayBucketLifecycle(data) {\n lifecycleEditor.bucket = data.bucket || lifecycleEditor.bucket;\n lifecycleEditor.rules = (data.rules || []).map(cloneLifecycleRule);\n lifecycleEditor.editingIndex = null;\n lifecycleEditor.editingRule = null;\n lifecycleEditor.rawXml = data.xml || '';\n // SeaweedFS doesn't support Transition rules (PutBucketLifecycleConfiguration\n // rejects them for Enabled rules), and the canonical rule shape the admin\n // edits has no field for one, so a Transition set by another client would\n // silently disappear on the next Save. Warn instead.\n // Matches <Transition> and <NoncurrentVersionTransition> however they are\n // spelled: with attributes, self-closed, or namespace-prefixed.\n lifecycleEditor.hasTransition = /<(\\w+:)?(NoncurrentVersion)?Transition[\\s>\\/]/.test(data.xml || '');\n renderLifecycleEditor();\n}\n\n// normalizeLifecycleStatus maps a stored status onto the two the editor can\n// show. The S3 API stores <Status> unvalidated, and the engine runs a rule\n// only on an exact \"Enabled\", so everything else is Disabled - collapsing it\n// here keeps an odd spelling from leaving both radios unchecked, which would\n// throw out of readLifecycleRuleFromForm and make the modal look dead.\nfunction normalizeLifecycleStatus(status) {\n return status === 'Enabled' ? 'Enabled' : 'Disabled';\n}\n\nfunction cloneLifecycleRule(r) {\n return {\n id: r.id || '',\n status: normalizeLifecycleStatus(r.status),\n prefix: r.prefix || '',\n tags: Object.assign({}, r.tags || {}),\n size_greater_than: r.size_greater_than || null,\n size_less_than: r.size_less_than || null,\n expiration_days: r.expiration_days || null,\n expiration_date: r.expiration_date || '',\n expired_object_delete_marker: !!r.expired_object_delete_marker,\n noncurrent_version_expiration_days: r.noncurrent_version_expiration_days || null,\n newer_noncurrent_versions: r.newer_noncurrent_versions || null,\n abort_multipart_days: r.abort_multipart_days || null,\n };\n}\n\nfunction blankLifecycleRule() {\n return {\n id: '', status: 'Enabled', prefix: '', tags: {},\n size_greater_than: null, size_less_than: null,\n expiration_days: null, expiration_date: '',\n expired_object_delete_marker: false,\n noncurrent_version_expiration_days: null, newer_noncurrent_versions: null,\n abort_multipart_days: null,\n };\n}\n\nfunction describeLifecycleScope(rule) {\n const parts = [];\n if (rule.prefix) {\n parts.push('<code>' + escapeHtml(rule.prefix) + '<\\/code>');\n }\n Object.entries(rule.tags || {}).forEach(([k, v]) => {\n parts.push('<span class=\"badge bg-light text-dark border\">' + escapeHtml(k) + '=' + escapeHtml(v) + '<\\/span>');\n });\n if (rule.size_greater_than) {\n parts.push('size &gt; ' + formatBytes(rule.size_greater_than));\n }\n if (rule.size_less_than) {\n parts.push('size &lt; ' + formatBytes(rule.size_less_than));\n }\n return parts.length ? parts.join(' ') : '<span class=\"text-muted\">Whole bucket<\\/span>';\n}\n\nfunction describeLifecycleActions(rule) {\n const actions = [];\n if (rule.expiration_days) {\n actions.push('Expire after ' + formatDays(rule.expiration_days));\n }\n if (rule.expiration_date) {\n actions.push('Expire on ' + escapeHtml(rule.expiration_date));\n }\n if (rule.expired_object_delete_marker) {\n actions.push('Remove expired object delete markers');\n }\n if (rule.noncurrent_version_expiration_days) {\n let action = 'Expire noncurrent versions after ' + formatDays(rule.noncurrent_version_expiration_days);\n if (rule.newer_noncurrent_versions) {\n action += ', keep ' + rule.newer_noncurrent_versions + ' newest';\n }\n actions.push(action);\n } else if (rule.newer_noncurrent_versions) {\n // Standalone (no expiration_days): the engine still recognizes this\n // as an action that expires noncurrent versions beyond the N newest.\n actions.push('Keep ' + rule.newer_noncurrent_versions + ' newest noncurrent versions');\n }\n if (rule.abort_multipart_days) {\n actions.push('Abort incomplete multipart uploads after ' + formatDays(rule.abort_multipart_days));\n }\n if (actions.length === 0) {\n return '<span class=\"text-muted\">None<\\/span>';\n }\n return actions.join('<br>');\n}\n\nfunction lifecycleRuleRowHtml(rule, idx) {\n const statusHtml = rule.status === 'Enabled'\n ? '<span class=\"badge bg-success\">Enabled<\\/span>'\n : '<span class=\"badge bg-secondary\">' + escapeHtml(rule.status) + '<\\/span>';\n return '<tr>' +\n '<td>' + (rule.id ? escapeHtml(rule.id) : '<span class=\"text-muted\">unnamed<\\/span>') + '<\\/td>' +\n '<td>' + statusHtml + '<\\/td>' +\n '<td>' + describeLifecycleScope(rule) + '<\\/td>' +\n '<td>' + describeLifecycleActions(rule) + '<\\/td>' +\n '<td class=\"text-end text-nowrap\">' +\n '<button type=\"button\" class=\"btn btn-sm btn-outline-secondary lifecycle-edit-rule-btn\" data-index=\"' + idx + '\" title=\"Edit rule\"><i class=\"fas fa-pen\"><\\/i><\\/button> ' +\n '<button type=\"button\" class=\"btn btn-sm btn-outline-danger lifecycle-delete-rule-btn\" data-index=\"' + idx + '\" title=\"Delete rule\"><i class=\"fas fa-trash\"><\\/i><\\/button>' +\n '<\\/td>' +\n '<\\/tr>';\n}\n\nfunction lifecycleRuleFormHtml() {\n const rule = lifecycleEditor.editingRule;\n const tagRowHtml = (k, v) =>\n '<div class=\"input-group input-group-sm mb-1 lifecycle-tag-row\">' +\n '<input type=\"text\" class=\"form-control lifecycle-tag-key\" placeholder=\"Key\" value=\"' + escapeHtml(k) + '\">' +\n '<input type=\"text\" class=\"form-control lifecycle-tag-value\" placeholder=\"Value\" value=\"' + escapeHtml(v) + '\">' +\n '<button type=\"button\" class=\"btn btn-outline-danger lifecycle-remove-tag-btn\"><i class=\"fas fa-times\"><\\/i><\\/button>' +\n '<\\/div>';\n const tagRows = Object.entries(rule.tags || {}).map(([k, v]) => tagRowHtml(k, v)).join('');\n\n return '' +\n '<div class=\"card mb-3\" id=\"lifecycleRuleForm\">' +\n '<div class=\"card-body\">' +\n '<h6 class=\"card-title\">' + (lifecycleEditor.editingIndex === 'new' ? 'Add rule' : 'Edit rule') + '<\\/h6>' +\n\n '<div class=\"row g-2 mb-2\">' +\n '<div class=\"col-md-6\">' +\n '<label class=\"form-label small\">ID (optional)<\\/label>' +\n '<input type=\"text\" class=\"form-control form-control-sm\" id=\"lifecycleRuleId\" value=\"' + escapeHtml(rule.id) + '\">' +\n '<\\/div>' +\n '<div class=\"col-md-6\">' +\n '<label class=\"form-label small d-block\">Status<\\/label>' +\n '<div class=\"form-check form-check-inline\">' +\n '<input class=\"form-check-input\" type=\"radio\" name=\"lifecycleRuleStatus\" id=\"lifecycleStatusEnabled\" value=\"Enabled\"' + (rule.status === 'Enabled' ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleStatusEnabled\">Enabled<\\/label>' +\n '<\\/div>' +\n '<div class=\"form-check form-check-inline\">' +\n '<input class=\"form-check-input\" type=\"radio\" name=\"lifecycleRuleStatus\" id=\"lifecycleStatusDisabled\" value=\"Disabled\"' + (rule.status === 'Disabled' ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleStatusDisabled\">Disabled<\\/label>' +\n '<\\/div>' +\n '<\\/div>' +\n '<\\/div>' +\n\n '<div class=\"mb-2\">' +\n '<label class=\"form-label small\">Prefix<\\/label>' +\n '<input type=\"text\" class=\"form-control form-control-sm\" id=\"lifecycleRulePrefix\" placeholder=\"logs/\" value=\"' + escapeHtml(rule.prefix) + '\">' +\n '<\\/div>' +\n\n '<div class=\"mb-2\">' +\n '<label class=\"form-label small d-block\">Tags<\\/label>' +\n '<div id=\"lifecycleTagRows\">' + tagRows + '<\\/div>' +\n '<button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"lifecycleAddTagBtn\"><i class=\"fas fa-plus me-1\"><\\/i>Add tag<\\/button>' +\n '<\\/div>' +\n\n '<div class=\"row g-2 mb-3\">' +\n '<div class=\"col-md-6\">' +\n '<label class=\"form-label small\">Size greater than (bytes)<\\/label>' +\n '<input type=\"number\" class=\"form-control form-control-sm\" id=\"lifecycleRuleSizeGT\" min=\"0\" step=\"1\" value=\"' + (rule.size_greater_than || '') + '\">' +\n '<\\/div>' +\n '<div class=\"col-md-6\">' +\n '<label class=\"form-label small\">Size less than (bytes)<\\/label>' +\n '<input type=\"number\" class=\"form-control form-control-sm\" id=\"lifecycleRuleSizeLT\" min=\"0\" step=\"1\" value=\"' + (rule.size_less_than || '') + '\">' +\n '<\\/div>' +\n '<\\/div>' +\n\n '<hr>' +\n '<h6 class=\"small text-muted text-uppercase\">Actions<\\/h6>' +\n\n '<div class=\"row g-2 align-items-center mb-2\">' +\n '<div class=\"col-auto\">' +\n '<div class=\"form-check\">' +\n '<input class=\"form-check-input\" type=\"checkbox\" id=\"lifecycleExpireDaysEnabled\"' + (rule.expiration_days ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleExpireDaysEnabled\">Expire after<\\/label>' +\n '<\\/div>' +\n '<\\/div>' +\n '<div class=\"col-auto\">' +\n '<input type=\"number\" class=\"form-control form-control-sm\" id=\"lifecycleExpireDays\" min=\"1\" step=\"1\" style=\"width: 6rem;\" value=\"' + (rule.expiration_days || '') + '\"' + (rule.expiration_days ? '' : ' disabled') + '>' +\n '<\\/div><div class=\"col-auto\">days<\\/div>' +\n '<\\/div>' +\n\n '<div class=\"row g-2 align-items-center mb-2\">' +\n '<div class=\"col-auto\">' +\n '<div class=\"form-check\">' +\n '<input class=\"form-check-input\" type=\"checkbox\" id=\"lifecycleExpireDateEnabled\"' + (rule.expiration_date ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleExpireDateEnabled\">Expire on date<\\/label>' +\n '<\\/div>' +\n '<\\/div>' +\n '<div class=\"col-auto\">' +\n '<input type=\"date\" class=\"form-control form-control-sm\" id=\"lifecycleExpireDate\" value=\"' + escapeHtml(rule.expiration_date) + '\"' + (rule.expiration_date ? '' : ' disabled') + '>' +\n '<\\/div>' +\n '<\\/div>' +\n\n '<div class=\"form-check mb-2\">' +\n '<input class=\"form-check-input\" type=\"checkbox\" id=\"lifecycleDeleteMarker\"' + (rule.expired_object_delete_marker ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleDeleteMarker\">Remove expired object delete markers<\\/label>' +\n '<\\/div>' +\n\n (() => {\n const noncurrentActive = !!(rule.noncurrent_version_expiration_days || rule.newer_noncurrent_versions);\n return '<div class=\"row g-2 align-items-center mb-2\">' +\n '<div class=\"col-auto\">' +\n '<div class=\"form-check\">' +\n '<input class=\"form-check-input\" type=\"checkbox\" id=\"lifecycleNoncurrentEnabled\"' + (noncurrentActive ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleNoncurrentEnabled\">Limit noncurrent versions<\\/label>' +\n '<\\/div>' +\n '<\\/div>' +\n '<div class=\"col-auto\">after<\\/div>' +\n '<div class=\"col-auto\">' +\n '<input type=\"number\" class=\"form-control form-control-sm\" id=\"lifecycleNoncurrentDays\" min=\"1\" step=\"1\" style=\"width: 6rem;\" value=\"' + (rule.noncurrent_version_expiration_days || '') + '\"' + (noncurrentActive ? '' : ' disabled') + '>' +\n '<\\/div><div class=\"col-auto\">days (optional), keep<\\/div>' +\n '<div class=\"col-auto\">' +\n '<input type=\"number\" class=\"form-control form-control-sm\" id=\"lifecycleNoncurrentKeep\" min=\"0\" step=\"1\" style=\"width: 6rem;\" value=\"' + (rule.newer_noncurrent_versions || '') + '\"' + (noncurrentActive ? '' : ' disabled') + '>' +\n '<\\/div><div class=\"col-auto\">newest (optional)<\\/div>' +\n '<\\/div>';\n })() +\n\n '<div class=\"row g-2 align-items-center mb-3\">' +\n '<div class=\"col-auto\">' +\n '<div class=\"form-check\">' +\n '<input class=\"form-check-input\" type=\"checkbox\" id=\"lifecycleAbortMPUEnabled\"' + (rule.abort_multipart_days ? ' checked' : '') + '>' +\n '<label class=\"form-check-label\" for=\"lifecycleAbortMPUEnabled\">Abort incomplete multipart uploads after<\\/label>' +\n '<\\/div>' +\n '<\\/div>' +\n '<div class=\"col-auto\">' +\n '<input type=\"number\" class=\"form-control form-control-sm\" id=\"lifecycleAbortMPUDays\" min=\"1\" step=\"1\" style=\"width: 6rem;\" value=\"' + (rule.abort_multipart_days || '') + '\"' + (rule.abort_multipart_days ? '' : ' disabled') + '>' +\n '<\\/div><div class=\"col-auto\">days<\\/div>' +\n '<\\/div>' +\n\n '<div class=\"text-end\">' +\n '<button type=\"button\" class=\"btn btn-sm btn-secondary\" id=\"lifecycleCancelRuleBtn\">Cancel<\\/button> ' +\n '<button type=\"button\" class=\"btn btn-sm btn-primary\" id=\"lifecycleSaveRuleBtn\">Save rule<\\/button>' +\n '<\\/div>' +\n '<\\/div>' +\n '<\\/div>';\n}\n\nfunction renderLifecycleEditor() {\n const container = document.getElementById('bucketLifecycleContent');\n const rowsHtml = lifecycleEditor.rules.map(lifecycleRuleRowHtml).join('') ||\n '<tr><td colspan=\"5\" class=\"text-center text-muted py-3\">No lifecycle rules<\\/td><\\/tr>';\n\n let html = '';\n if (lifecycleEditor.hasTransition) {\n html += '<div class=\"alert alert-warning small\">' +\n '<i class=\"fas fa-triangle-exclamation me-1\"><\\/i>' +\n 'This bucket has a Transition rule set outside the admin (SeaweedFS does not support storage class transitions). Saving from here will drop it.' +\n '<\\/div>';\n }\n\n html += '<div class=\"table-responsive mb-3\">' +\n '<table class=\"table table-sm align-middle\">' +\n '<thead><tr><th>Rule<\\/th><th>Status<\\/th><th>Scope<\\/th><th>Actions<\\/th><th><\\/th><\\/tr><\\/thead>' +\n '<tbody>' + rowsHtml + '<\\/tbody>' +\n '<\\/table>' +\n '<\\/div>' +\n '<button type=\"button\" class=\"btn btn-sm btn-outline-primary mb-3\" id=\"lifecycleAddRuleBtn\">' +\n '<i class=\"fas fa-plus me-1\"><\\/i>Add rule' +\n '<\\/button>';\n\n if (lifecycleEditor.editingIndex !== null) {\n html += lifecycleRuleFormHtml();\n }\n\n if (lifecycleEditor.rawXml) {\n html += '<details class=\"mt-2\">' +\n '<summary class=\"text-muted small\">Raw XML (as currently stored)<\\/summary>' +\n '<pre class=\"bg-light border rounded p-2 mt-2 small mb-0\">' + escapeHtml(lifecycleEditor.rawXml) + '<\\/pre>' +\n '<\\/details>';\n }\n\n container.innerHTML = html;\n bindLifecycleEditorEvents();\n}\n\nfunction bindLifecycleToggle(checkboxId, fieldId, mutuallyExclusiveId) {\n const checkbox = document.getElementById(checkboxId);\n const field = document.getElementById(fieldId);\n if (!checkbox || !field) return;\n checkbox.addEventListener('change', function() {\n field.disabled = !this.checked;\n if (this.checked && mutuallyExclusiveId) {\n const other = document.getElementById(mutuallyExclusiveId);\n if (other && other.checked) {\n other.checked = false;\n other.dispatchEvent(new Event('change'));\n }\n }\n });\n}\n\nfunction bindLifecycleEditorEvents() {\n const addBtn = document.getElementById('lifecycleAddRuleBtn');\n if (addBtn) {\n addBtn.addEventListener('click', function() {\n // Fold in any rule already being edited before switching forms,\n // so an invalid in-progress draft isn't silently discarded.\n if (!commitOpenLifecycleRuleForm()) return;\n lifecycleEditor.editingIndex = 'new';\n lifecycleEditor.editingRule = blankLifecycleRule();\n renderLifecycleEditor();\n });\n }\n\n document.querySelectorAll('.lifecycle-edit-rule-btn').forEach(btn => {\n btn.addEventListener('click', function() {\n const idx = parseInt(this.dataset.index, 10);\n // Same as above: committing never shifts indices (it either\n // pushes a new rule at the end or replaces one in place), so\n // idx captured above is still valid after this call.\n if (!commitOpenLifecycleRuleForm()) return;\n lifecycleEditor.editingIndex = idx;\n lifecycleEditor.editingRule = cloneLifecycleRule(lifecycleEditor.rules[idx]);\n renderLifecycleEditor();\n });\n });\n\n document.querySelectorAll('.lifecycle-delete-rule-btn').forEach(btn => {\n btn.addEventListener('click', function() {\n const idx = parseInt(this.dataset.index, 10);\n // Fold in an open form first, like every other transition does:\n // re-rendering after the splice would otherwise redraw it from the\n // snapshot taken when editing began and lose what was typed.\n if (lifecycleEditor.editingIndex !== null && lifecycleEditor.editingIndex !== idx) {\n if (!commitOpenLifecycleRuleForm()) return;\n }\n lifecycleEditor.rules.splice(idx, 1);\n // Deleting a rule shifts every later index down by one, so an\n // open edit form must follow its rule rather than silently\n // start targeting whatever now sits at its old index.\n if (lifecycleEditor.editingIndex === idx) {\n lifecycleEditor.editingIndex = null;\n lifecycleEditor.editingRule = null;\n } else if (typeof lifecycleEditor.editingIndex === 'number' && lifecycleEditor.editingIndex > idx) {\n lifecycleEditor.editingIndex -= 1;\n }\n renderLifecycleEditor();\n });\n });\n\n const cancelBtn = document.getElementById('lifecycleCancelRuleBtn');\n if (cancelBtn) {\n cancelBtn.addEventListener('click', function() {\n lifecycleEditor.editingIndex = null;\n lifecycleEditor.editingRule = null;\n renderLifecycleEditor();\n });\n }\n\n const addTagBtn = document.getElementById('lifecycleAddTagBtn');\n if (addTagBtn) {\n addTagBtn.addEventListener('click', function() {\n const rows = document.getElementById('lifecycleTagRows');\n const row = document.createElement('div');\n row.className = 'input-group input-group-sm mb-1 lifecycle-tag-row';\n row.innerHTML =\n '<input type=\"text\" class=\"form-control lifecycle-tag-key\" placeholder=\"Key\">' +\n '<input type=\"text\" class=\"form-control lifecycle-tag-value\" placeholder=\"Value\">' +\n '<button type=\"button\" class=\"btn btn-outline-danger lifecycle-remove-tag-btn\"><i class=\"fas fa-times\"><\\/i><\\/button>';\n rows.appendChild(row);\n row.querySelector('.lifecycle-remove-tag-btn').addEventListener('click', function() {\n row.remove();\n });\n });\n }\n\n document.querySelectorAll('.lifecycle-remove-tag-btn').forEach(btn => {\n btn.addEventListener('click', function() {\n this.closest('.lifecycle-tag-row').remove();\n });\n });\n\n bindLifecycleToggle('lifecycleExpireDaysEnabled', 'lifecycleExpireDays', 'lifecycleExpireDateEnabled');\n bindLifecycleToggle('lifecycleExpireDateEnabled', 'lifecycleExpireDate', 'lifecycleExpireDaysEnabled');\n bindLifecycleToggle('lifecycleNoncurrentEnabled', 'lifecycleNoncurrentDays');\n bindLifecycleToggle('lifecycleNoncurrentEnabled', 'lifecycleNoncurrentKeep');\n bindLifecycleToggle('lifecycleAbortMPUEnabled', 'lifecycleAbortMPUDays');\n\n const saveRuleBtn = document.getElementById('lifecycleSaveRuleBtn');\n if (saveRuleBtn) {\n saveRuleBtn.addEventListener('click', saveLifecycleRuleFromForm);\n }\n}\n\n// readLifecycleRuleFromForm builds and validates a rule from the currently\n// open edit form's DOM inputs. Returns { rule: null, error: '...' } when the\n// form doesn't hold a valid rule, without mutating any state.\nfunction readLifecycleRuleFromForm() {\n const id = document.getElementById('lifecycleRuleId').value.trim();\n const status = document.querySelector('input[name=\"lifecycleRuleStatus\"]:checked').value;\n const prefix = document.getElementById('lifecycleRulePrefix').value.trim();\n\n const tags = {};\n document.querySelectorAll('#lifecycleTagRows .lifecycle-tag-row').forEach(row => {\n const key = row.querySelector('.lifecycle-tag-key').value.trim();\n const value = row.querySelector('.lifecycle-tag-value').value.trim();\n if (key) {\n tags[key] = value;\n }\n });\n\n const sizeGT = parseInt(document.getElementById('lifecycleRuleSizeGT').value, 10) || 0;\n const sizeLT = parseInt(document.getElementById('lifecycleRuleSizeLT').value, 10) || 0;\n\n const expireDaysEnabled = document.getElementById('lifecycleExpireDaysEnabled').checked;\n const expireDateEnabled = document.getElementById('lifecycleExpireDateEnabled').checked;\n const expirationDays = expireDaysEnabled ? (parseInt(document.getElementById('lifecycleExpireDays').value, 10) || 0) : 0;\n const expirationDate = expireDateEnabled ? document.getElementById('lifecycleExpireDate').value : '';\n\n const deleteMarker = document.getElementById('lifecycleDeleteMarker').checked;\n\n const noncurrentEnabled = document.getElementById('lifecycleNoncurrentEnabled').checked;\n const noncurrentDays = noncurrentEnabled ? (parseInt(document.getElementById('lifecycleNoncurrentDays').value, 10) || 0) : 0;\n const noncurrentKeep = noncurrentEnabled ? (parseInt(document.getElementById('lifecycleNoncurrentKeep').value, 10) || 0) : 0;\n\n const abortEnabled = document.getElementById('lifecycleAbortMPUEnabled').checked;\n const abortDays = abortEnabled ? (parseInt(document.getElementById('lifecycleAbortMPUDays').value, 10) || 0) : 0;\n\n if (expireDaysEnabled && expirationDays <= 0) {\n return { rule: null, error: 'Enter a valid number of days for expiration.' };\n }\n if (expireDateEnabled && !expirationDate) {\n return { rule: null, error: 'Enter a valid expiration date.' };\n }\n if (noncurrentEnabled && noncurrentDays <= 0 && noncurrentKeep <= 0) {\n return { rule: null, error: 'Enter a number of days and/or a newest-versions-to-keep count for noncurrent version handling.' };\n }\n if (abortEnabled && abortDays <= 0) {\n return { rule: null, error: 'Enter a valid number of days for aborting incomplete multipart uploads.' };\n }\n if (!expireDaysEnabled && !expireDateEnabled && !deleteMarker && !noncurrentEnabled && !abortEnabled) {\n return { rule: null, error: 'Select at least one action for this rule.' };\n }\n // The server rejects this combination too; catching it here names the two\n // fields instead of surfacing a 400 after the whole set is submitted.\n if (deleteMarker && (expireDaysEnabled || expireDateEnabled)) {\n return { rule: null, error: 'Removing expired object delete markers cannot be combined with an expiration.' };\n }\n if (sizeGT > 0 && sizeLT > 0 && sizeGT >= sizeLT) {\n return { rule: null, error: '\"Size greater than\" must be less than \"size less than\".' };\n }\n\n return {\n rule: {\n id: id,\n status: status,\n prefix: prefix,\n tags: tags,\n size_greater_than: sizeGT > 0 ? sizeGT : null,\n size_less_than: sizeLT > 0 ? sizeLT : null,\n expiration_days: expirationDays > 0 ? expirationDays : null,\n expiration_date: expirationDate || '',\n expired_object_delete_marker: deleteMarker,\n noncurrent_version_expiration_days: noncurrentDays > 0 ? noncurrentDays : null,\n newer_noncurrent_versions: noncurrentKeep > 0 ? noncurrentKeep : null,\n abort_multipart_days: abortDays > 0 ? abortDays : null,\n },\n error: null,\n };\n}\n\nfunction saveLifecycleRuleFromForm() {\n const { rule, error } = readLifecycleRuleFromForm();\n if (error) {\n alert(error);\n return;\n }\n\n if (lifecycleEditor.editingIndex === 'new') {\n lifecycleEditor.rules.push(rule);\n } else {\n lifecycleEditor.rules[lifecycleEditor.editingIndex] = rule;\n }\n lifecycleEditor.editingIndex = null;\n lifecycleEditor.editingRule = null;\n renderLifecycleEditor();\n}\n\n// commitOpenLifecycleRuleForm folds an in-progress add/edit form into\n// lifecycleEditor.rules before the whole rule set is sent to the server, so\n// clicking the modal's \"Save\" without first clicking \"Save rule\" doesn't\n// silently drop the open edit. Returns false (and leaves the form open) when\n// the open form doesn't hold a valid rule, so the caller can abort the save.\nfunction commitOpenLifecycleRuleForm() {\n if (lifecycleEditor.editingIndex === null) {\n return true;\n }\n\n const { rule, error } = readLifecycleRuleFromForm();\n if (error) {\n alert(error);\n return false;\n }\n\n if (lifecycleEditor.editingIndex === 'new') {\n lifecycleEditor.rules.push(rule);\n } else {\n lifecycleEditor.rules[lifecycleEditor.editingIndex] = rule;\n }\n lifecycleEditor.editingIndex = null;\n lifecycleEditor.editingRule = null;\n renderLifecycleEditor();\n return true;\n}\n\n function goToPage(page) {\n const url = new URL(window.location);\n url.searchParams.set('page', page);\n window.location.href = url.toString();\n }\n\n function changePageSize() {\n const pageSize = document.getElementById('pageSizeSelect').value;\n const url = new URL(window.location);\n url.searchParams.set('pageSize', pageSize);\n url.searchParams.set('page', '1');\n window.location.href = url.toString();\n }\n\n function sortTable(column) {\n const url = new URL(window.location);\n const currentSort = url.searchParams.get('sortBy');\n const currentOrder = url.searchParams.get('sortOrder') || 'asc';\n\n let newOrder = 'asc';\n if (currentSort === column && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n\n url.searchParams.set('sortBy', column);\n url.searchParams.set('sortOrder', newOrder);\n url.searchParams.set('page', '1');\n window.location.href = url.toString();\n }\n\n function exportBucketList() {\n // RFC 4180 compliant CSV escaping: escape double quotes by doubling them\n function escapeCsvField(value) {\n const str = String(value ?? '');\n if (str.includes(',') || str.includes('\"') || str.includes('\\n') || str.includes('\\r')) {\n return '\"' + str.replace(/\"/g, '\"\"') + '\"';\n }\n return '\"' + str + '\"';\n }\n\n // Fetch all buckets from the API (not just the current page)\n fetch(basePath('/api/s3/buckets'))\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error exporting buckets: ' + data.error);\n return;\n }\n\n const buckets = data.buckets || [];\n const csvContent = \"data:text/csv;charset=utf-8,\" +\n \"Name,Owner,Logical Size,Physical Size,Created,Quota,Versioning,Object Lock\\n\" +\n buckets.map(b => [\n escapeCsvField(b.name),\n escapeCsvField(b.owner),\n escapeCsvField(formatBytes(b.logical_size)),\n escapeCsvField(formatBytes(b.physical_size)),\n escapeCsvField(b.created_at),\n escapeCsvField(b.quota_enabled ? formatBytes(b.quota) : 'No quota'),\n escapeCsvField(b.versioning_status || 'Not configured'),\n escapeCsvField(b.object_lock_enabled ? 'Enabled' : 'Not configured')\n ].join(',')).join(\"\\n\");\n\n const encodedUri = encodeURI(csvContent);\n const link = document.createElement(\"a\");\n link.setAttribute(\"href\", encodedUri);\n link.setAttribute(\"download\", \"buckets.csv\");\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error exporting buckets: ' + error.message);\n });\n }\n </script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
diff --git a/weed/admin/view/app/s3tables_buckets.templ b/weed/admin/view/app/s3tables_buckets.templ
index b6458e41dd..9530175d06 100644
--- a/weed/admin/view/app/s3tables_buckets.templ
+++ b/weed/admin/view/app/s3tables_buckets.templ
@@ -150,6 +150,7 @@ templ S3TablesBuckets(data dash.S3TablesBucketsData) {
<th>ARN</th>
<th>Catalog Endpoint</th>
<th>Created</th>
+ <th>Policy</th>
<th>Actions</th>
</tr>
</thead>
@@ -164,6 +165,20 @@ templ S3TablesBuckets(data dash.S3TablesBucketsData) {
<td class="text-muted small">{ bucket.ARN }</td>
<td><code class="small">{ bucketCatalogPath(bucket.Format, bucket.Name) }</code></td>
<td>{ bucket.CreatedAt.Format("2006-01-02 15:04") }</td>
+ <td>
+ if bucket.PolicyStatementCount > 0 {
+ <button type="button" class="badge bg-primary border-0 s3tables-bucket-policy-btn"
+ data-bucket-arn={ bucket.ARN } title="View Bucket Policy">
+ if bucket.PolicyStatementCount == 1 {
+ 1 statement
+ } else {
+ { fmt.Sprintf("%d statements", bucket.PolicyStatementCount) }
+ }
+ </button>
+ } else {
+ <span class="text-muted">Not configured</span>
+ }
+ </td>
<td>
<div class="btn-group btn-group-sm" role="group">
{{ bucketName, parseErr := s3tables.ParseBucketNameFromARN(bucket.ARN) }}
@@ -191,7 +206,7 @@ templ S3TablesBuckets(data dash.S3TablesBucketsData) {
}
if len(data.Buckets) == 0 {
<tr>
- <td colspan="7" class="text-center text-muted py-4">
+ <td colspan="8" class="text-center text-muted py-4">
<i class="fas fa-table fa-3x mb-3 text-muted"></i>
<div>
<h5>No table buckets found</h5>
@@ -395,8 +410,10 @@ dataset = lance.dataset(table.location, storage_options=table.storage_options)`
</div>
</div>
</div>
+ @PolicyDatalists()
+
<div class="modal fade" id="s3tablesBucketPolicyModal" tabindex="-1" aria-labelledby="s3tablesBucketPolicyModalLabel" 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="s3tablesBucketPolicyModalLabel">
@@ -407,9 +424,24 @@ dataset = lance.dataset(table.location, storage_options=table.storage_options)`
<form id="s3tablesBucketPolicyForm">
<div class="modal-body">
<input type="hidden" id="s3tablesBucketPolicyArn" name="bucket_arn"/>
- <div class="mb-3">
- <label for="s3tablesBucketPolicyText" class="form-label">Policy JSON</label>
- <textarea class="form-control" id="s3tablesBucketPolicyText" name="policy" rows="12" placeholder="{ }"></textarea>
+ <ul class="nav nav-tabs" role="tablist">
+ <li class="nav-item" role="presentation">
+ <button class="nav-link active" id="s3tablesBucketPolicyEditorTabBtn" type="button" data-bs-toggle="tab" data-bs-target="#s3tablesBucketPolicyEditorTab" role="tab" aria-controls="s3tablesBucketPolicyEditorTab" aria-selected="true">Editor</button>
+ </li>
+ <li class="nav-item" role="presentation">
+ <button class="nav-link" id="s3tablesBucketPolicyJsonTabBtn" type="button" data-bs-toggle="tab" data-bs-target="#s3tablesBucketPolicyJsonTab" role="tab" aria-controls="s3tablesBucketPolicyJsonTab" aria-selected="false">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="s3tablesBucketPolicyEditorTab" role="tabpanel" aria-labelledby="s3tablesBucketPolicyEditorTabBtn">
+ <div id="s3tablesBucketPolicyEditorBody"></div>
+ <button type="button" class="btn btn-sm btn-outline-secondary" id="s3tablesBucketPolicyAddStatementBtn">
+ <i class="fas fa-plus me-1"></i>Add statement
+ </button>
+ </div>
+ <div class="tab-pane fade" id="s3tablesBucketPolicyJsonTab" role="tabpanel" aria-labelledby="s3tablesBucketPolicyJsonTabBtn">
+ <textarea class="form-control" id="s3tablesBucketPolicyText" name="policy" rows="12" placeholder="{ }"></textarea>
+ </div>
</div>
<div class="form-text">
Provide a policy JSON; use Delete Policy to remove the policy.
diff --git a/weed/admin/view/app/s3tables_buckets_templ.go b/weed/admin/view/app/s3tables_buckets_templ.go
index 6498559aea..5936465aea 100644
--- a/weed/admin/view/app/s3tables_buckets_templ.go
+++ b/weed/admin/view/app/s3tables_buckets_templ.go
@@ -49,7 +49,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var2 templ.SafeURL
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//localhost:%d/v1/config", data.IcebergPort)))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 24, Col: 119}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 24, Col: 119}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil {
@@ -68,7 +68,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var3 templ.SafeURL
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//localhost:%d/v1/table", data.LancePort)))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 31, Col: 114}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 31, Col: 114}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
@@ -86,7 +86,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.IcebergPort))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 38, Col: 91}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 38, Col: 91}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var4)
if templ_7745c5c3_Err != nil {
@@ -99,7 +99,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.LancePort))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 38, Col: 145}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 38, Col: 145}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var5)
if templ_7745c5c3_Err != nil {
@@ -122,7 +122,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.IcebergPort))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 52, Col: 105}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 52, Col: 105}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var6)
if templ_7745c5c3_Err != nil {
@@ -135,7 +135,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("http://localhost:%d", data.IcebergPort))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 52, Col: 162}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 52, Col: 162}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
@@ -154,7 +154,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.LancePort))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 58, Col: 103}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 58, Col: 103}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var8)
if templ_7745c5c3_Err != nil {
@@ -167,7 +167,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("http://localhost:%d", data.LancePort))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 58, Col: 158}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 58, Col: 158}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
@@ -196,7 +196,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalBuckets))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 81, Col: 47}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 81, Col: 47}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
@@ -209,7 +209,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 100, Col: 54}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 100, Col: 54}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
if templ_7745c5c3_Err != nil {
@@ -223,7 +223,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var12 string
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.IcebergPort))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 120, Col: 47}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 120, Col: 47}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
if templ_7745c5c3_Err != nil {
@@ -235,7 +235,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "</div></div><div class=\"col-auto\"><i class=\"fas fa-snowflake fa-2x text-gray-300\"></i></div></div></div></div></div></div><div class=\"row\"><div class=\"col-12\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3 d-flex flex-row align-items-center justify-content-between\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-table me-2\"></i>Table Buckets</h6></div><div class=\"card-body\"><div class=\"table-responsive\"><table class=\"table table-hover\" width=\"100%\" cellspacing=\"0\" id=\"s3tablesBucketsTable\"><thead><tr><th>Name</th><th>Format</th><th>Owner</th><th>ARN</th><th>Catalog Endpoint</th><th>Created</th><th>Actions</th></tr></thead> <tbody>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "</div></div><div class=\"col-auto\"><i class=\"fas fa-snowflake fa-2x text-gray-300\"></i></div></div></div></div></div></div><div class=\"row\"><div class=\"col-12\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3 d-flex flex-row align-items-center justify-content-between\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-table me-2\"></i>Table Buckets</h6></div><div class=\"card-body\"><div class=\"table-responsive\"><table class=\"table table-hover\" width=\"100%\" cellspacing=\"0\" id=\"s3tablesBucketsTable\"><thead><tr><th>Name</th><th>Format</th><th>Owner</th><th>ARN</th><th>Catalog Endpoint</th><th>Created</th><th>Policy</th><th>Actions</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -247,7 +247,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 159, Col: 28}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 160, Col: 28}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil {
@@ -269,7 +269,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.ResolveAttributeValue(templ.CSSClasses(templ_7745c5c3_Var14).String())
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 1, Col: 0}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 1, Col: 0}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var15)
if templ_7745c5c3_Err != nil {
@@ -282,7 +282,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.ResolveAttributeValue(formatBadgeTitle(bucket.Format))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 161, Col: 99}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 162, Col: 99}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var16)
if templ_7745c5c3_Err != nil {
@@ -295,7 +295,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(formatLabel(bucket.Format))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 161, Col: 130}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 162, Col: 130}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
@@ -308,7 +308,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.OwnerAccountID)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 163, Col: 38}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 164, Col: 38}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
if templ_7745c5c3_Err != nil {
@@ -321,7 +321,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.ARN)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 164, Col: 52}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 165, Col: 52}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
@@ -334,7 +334,7 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(bucketCatalogPath(bucket.Format, bucket.Name))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 165, Col: 82}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 166, Col: 82}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
@@ -347,120 +347,168 @@ func S3TablesBuckets(data dash.S3TablesBucketsData) templ.Component {
var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.CreatedAt.Format("2006-01-02 15:04"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 166, Col: 60}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 167, Col: 60}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "</td><td><div class=\"btn-group btn-group-sm\" role=\"group\">")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "</td><td>")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ if bucket.PolicyStatementCount > 0 {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "<button type=\"button\" class=\"badge bg-primary border-0 s3tables-bucket-policy-btn\" data-bucket-arn=\"")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var22 string
+ templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.ARN)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 171, Col: 43}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var22)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\" title=\"View Bucket Policy\">")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ if bucket.PolicyStatementCount == 1 {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "1 statement")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ } else {
+ var templ_7745c5c3_Var23 string
+ templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d statements", bucket.PolicyStatementCount))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 175, Col: 74}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "</button>")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ } else {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "<span class=\"text-muted\">Not configured</span>")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "</td><td><div class=\"btn-group btn-group-sm\" role=\"group\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
bucketName, parseErr := s3tables.ParseBucketNameFromARN(bucket.ARN)
if parseErr == nil {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "<a class=\"btn btn-outline-primary btn-sm\" href=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "<a class=\"btn btn-outline-primary btn-sm\" href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var22 templ.SafeURL
- templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/object-store/s3tables/buckets/%s/namespaces", url.PathEscape(bucketName))))
+ var templ_7745c5c3_Var24 templ.SafeURL
+ templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/object-store/s3tables/buckets/%s/namespaces", url.PathEscape(bucketName))))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 171, Col: 166}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 186, Col: 166}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\"><i class=\"fas fa-folder-open\"></i></a> ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "\"><i class=\"fas fa-folder-open\"></i></a> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" disabled title=\"Invalid bucket ARN\"><i class=\"fas fa-folder-open\"></i></button> ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" disabled title=\"Invalid bucket ARN\"><i class=\"fas fa-folder-open\"></i></button> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "<button type=\"button\" class=\"btn btn-outline-success btn-sm s3tables-tags-btn\" data-resource-arn=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "<button type=\"button\" class=\"btn btn-outline-success btn-sm s3tables-tags-btn\" data-resource-arn=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var23 string
- templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.ARN)
+ var templ_7745c5c3_Var25 string
+ templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.ARN)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 179, Col: 122}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 194, Col: 122}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var23)
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var25)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "\" title=\"Tags\"><i class=\"fas fa-tags\"></i></button> <button type=\"button\" class=\"btn btn-outline-info btn-sm s3tables-bucket-policy-btn\" data-bucket-arn=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "\" title=\"Tags\"><i class=\"fas fa-tags\"></i></button> <button type=\"button\" class=\"btn btn-outline-info btn-sm s3tables-bucket-policy-btn\" data-bucket-arn=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var24 string
- templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.ARN)
+ var templ_7745c5c3_Var26 string
+ templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.ARN)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 182, Col: 126}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 197, Col: 126}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var24)
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var26)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "\" title=\"Bucket Policy\"><i class=\"fas fa-shield-alt\"></i></button> <button type=\"button\" class=\"btn btn-outline-danger btn-sm s3tables-delete-bucket-btn\" data-bucket-arn=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "\" title=\"Bucket Policy\"><i class=\"fas fa-shield-alt\"></i></button> <button type=\"button\" class=\"btn btn-outline-danger btn-sm s3tables-delete-bucket-btn\" data-bucket-arn=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var25 string
- templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.ARN)
+ var templ_7745c5c3_Var27 string
+ templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.ARN)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 185, Col: 128}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 200, Col: 128}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var25)
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var27)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "\" data-bucket-name=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var26 string
- templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.Name)
+ var templ_7745c5c3_Var28 string
+ templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.ResolveAttributeValue(bucket.Name)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 185, Col: 161}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 200, Col: 161}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var26)
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var28)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "\" title=\"Delete\"><i class=\"fas fa-trash\"></i></button></div></td></tr>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "\" title=\"Delete\"><i class=\"fas fa-trash\"></i></button></div></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if len(data.Buckets) == 0 {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "<tr><td colspan=\"7\" class=\"text-center text-muted py-4\"><i class=\"fas fa-table fa-3x mb-3 text-muted\"></i><div><h5>No table buckets found</h5><p>Create your first S3 Tables bucket to get started.</p><button type=\"button\" class=\"btn btn-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#createS3TablesBucketModal\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></td></tr>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "<tr><td colspan=\"8\" class=\"text-center text-muted py-4\"><i class=\"fas fa-table fa-3x mb-3 text-muted\"></i><div><h5>No table buckets found</h5><p>Create your first S3 Tables bucket to get started.</p><button type=\"button\" class=\"btn btn-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#createS3TablesBucketModal\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "</tbody></table></div></div></div></div></div>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "</tbody></table></div></div></div></div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.IcebergPort > 0 || data.LancePort > 0 {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "<div class=\"row\"><div class=\"col-12\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-code me-2\"></i>Client Examples</h6></div><div class=\"card-body\">")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "<div class=\"row\"><div class=\"col-12\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-code me-2\"></i>Client Examples</h6></div><div class=\"card-body\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.IcebergPort > 0 {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "<h6><span class=\"badge bg-primary me-2\">ICEBERG</span>DuckDB</h6><pre class=\"bg-light p-3 border rounded\"><code id=\"s3tables-duckdb-example\">")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "<h6><span class=\"badge bg-primary me-2\">ICEBERG</span>DuckDB</h6><pre class=\"bg-light p-3 border rounded\"><code id=\"s3tables-duckdb-example\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var27 string
- templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(`INSTALL iceberg;
+ var templ_7745c5c3_Var29 string
+ templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(`INSTALL iceberg;
LOAD iceberg;
CREATE SECRET (
@@ -471,18 +519,18 @@ CREATE SECRET (
SELECT * FROM iceberg_scan('s3://my-table-bucket/my-namespace/my-table');`)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 236, Col: 74}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 251, Col: 74}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "</code></pre><h6 class=\"mt-4\"><span class=\"badge bg-primary me-2\">ICEBERG</span>Python (PyIceberg)</h6><pre class=\"bg-light p-3 border rounded\"><code id=\"s3tables-pyiceberg-example\">")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "</code></pre><h6 class=\"mt-4\"><span class=\"badge bg-primary me-2\">ICEBERG</span>Python (PyIceberg)</h6><pre class=\"bg-light p-3 border rounded\"><code id=\"s3tables-pyiceberg-example\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var28 string
- templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(`from pyiceberg.catalog import load_catalog
+ var templ_7745c5c3_Var30 string
+ templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(`from pyiceberg.catalog import load_catalog
catalog = load_catalog(
name="seaweedfs",
@@ -495,60 +543,60 @@ catalog = load_catalog(
namespaces = catalog.list_namespaces()`)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 253, Col: 39}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 268, Col: 39}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "</code></pre>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "</code></pre>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if data.LancePort > 0 {
- var templ_7745c5c3_Var29 = []any{templ.KV("mt-4", data.IcebergPort > 0)}
- templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_Var29...)
+ var templ_7745c5c3_Var31 = []any{templ.KV("mt-4", data.IcebergPort > 0)}
+ templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_Var31...)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "<h6 class=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "<h6 class=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var30 string
- templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.ResolveAttributeValue(templ.CSSClasses(templ_7745c5c3_Var29).String())
+ var templ_7745c5c3_Var32 string
+ templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.ResolveAttributeValue(templ.CSSClasses(templ_7745c5c3_Var31).String())
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 1, Col: 0}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 1, Col: 0}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var30)
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var32)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "\"><span class=\"badge bg-success me-2\">LANCE</span>Python (lance-namespace)</h6><pre class=\"bg-light p-3 border rounded\"><code id=\"s3tables-lance-namespace-example\">")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "\"><span class=\"badge bg-success me-2\">LANCE</span>Python (lance-namespace)</h6><pre class=\"bg-light p-3 border rounded\"><code id=\"s3tables-lance-namespace-example\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var31 string
- templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(`from lance_namespace import connect
+ var templ_7745c5c3_Var33 string
+ templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(`from lance_namespace import connect
ns = connect("rest", {"uri": "http://localhost:` + fmt.Sprintf("%d", data.LancePort) + `"})
ns.list_namespaces(id=["my-table-bucket"])
ns.describe_table(id=["my-table-bucket", "my-namespace", "my-table"])`)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 266, Col: 70}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 281, Col: 70}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "</code></pre><h6 class=\"mt-4\"><span class=\"badge bg-success me-2\">LANCE</span>Python (pylance)</h6><pre class=\"bg-light p-3 border rounded\"><code id=\"s3tables-pylance-example\">")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "</code></pre><h6 class=\"mt-4\"><span class=\"badge bg-success me-2\">LANCE</span>Python (pylance)</h6><pre class=\"bg-light p-3 border rounded\"><code id=\"s3tables-pylance-example\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var32 string
- templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(`import lance
+ var templ_7745c5c3_Var34 string
+ templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(`import lance
from lance_namespace import connect
ns = connect("rest", {"uri": "http://localhost:` + fmt.Sprintf("%d", data.LancePort) + `"})
@@ -557,84 +605,92 @@ table = ns.describe_table(id=["my-table-bucket", "my-namespace", "my-table"])
# The namespace vends both the location and the credentials to read it.
dataset = lance.dataset(table.location, storage_options=table.storage_options)`)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 279, Col: 79}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 294, Col: 79}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "</code></pre>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "</code></pre>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "<script>\n\t\t\t\t\t\t\t\tconst s3tablesExamplesHost = window.location.hostname;\n\t\t\t\t\t\t\t\tconst s3tablesExamples = [\n\t\t\t\t\t\t\t\t\tdocument.getElementById('s3tables-duckdb-example'),\n\t\t\t\t\t\t\t\t\tdocument.getElementById('s3tables-pyiceberg-example'),\n\t\t\t\t\t\t\t\t\tdocument.getElementById('s3tables-lance-namespace-example'),\n\t\t\t\t\t\t\t\t\tdocument.getElementById('s3tables-pylance-example')\n\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\ts3tablesExamples.forEach(example => {\n\t\t\t\t\t\t\t\t\tif (!example) {\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\texample.textContent = example.textContent.replaceAll('localhost', s3tablesExamplesHost);\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t</script></div></div></div></div>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "<script>\n\t\t\t\t\t\t\t\tconst s3tablesExamplesHost = window.location.hostname;\n\t\t\t\t\t\t\t\tconst s3tablesExamples = [\n\t\t\t\t\t\t\t\t\tdocument.getElementById('s3tables-duckdb-example'),\n\t\t\t\t\t\t\t\t\tdocument.getElementById('s3tables-pyiceberg-example'),\n\t\t\t\t\t\t\t\t\tdocument.getElementById('s3tables-lance-namespace-example'),\n\t\t\t\t\t\t\t\t\tdocument.getElementById('s3tables-pylance-example')\n\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\ts3tablesExamples.forEach(example => {\n\t\t\t\t\t\t\t\t\tif (!example) {\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\texample.textContent = example.textContent.replaceAll('localhost', s3tablesExamplesHost);\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t</script></div></div></div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "</div><div class=\"modal fade\" id=\"createS3TablesBucketModal\" tabindex=\"-1\" aria-labelledby=\"createS3TablesBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createS3TablesBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create Table Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createS3TablesBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"s3tablesBucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesBucketName\" name=\"name\" placeholder=\"table-bucket-name\" required></div><div class=\"mb-3\"><label class=\"form-label\">Table Format</label><div class=\"row g-2\" id=\"s3tablesBucketFormatPicker\"><div class=\"col-6\">")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "</div><div class=\"modal fade\" id=\"createS3TablesBucketModal\" tabindex=\"-1\" aria-labelledby=\"createS3TablesBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createS3TablesBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create Table Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createS3TablesBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"s3tablesBucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesBucketName\" name=\"name\" placeholder=\"table-bucket-name\" required></div><div class=\"mb-3\"><label class=\"form-label\">Table Format</label><div class=\"row g-2\" id=\"s3tablesBucketFormatPicker\"><div class=\"col-6\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.IcebergPort > 0 {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "<input type=\"radio\" class=\"btn-check\" name=\"format\" id=\"s3tablesBucketFormatIceberg\" value=\"ICEBERG\" checked> ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "<input type=\"radio\" class=\"btn-check\" name=\"format\" id=\"s3tablesBucketFormatIceberg\" value=\"ICEBERG\" checked> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "<input type=\"radio\" class=\"btn-check\" name=\"format\" id=\"s3tablesBucketFormatIceberg\" value=\"ICEBERG\" disabled> ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "<input type=\"radio\" class=\"btn-check\" name=\"format\" id=\"s3tablesBucketFormatIceberg\" value=\"ICEBERG\" disabled> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "<label class=\"btn btn-outline-primary w-100 text-start p-3\" for=\"s3tablesBucketFormatIceberg\"><span class=\"d-block fw-semibold\"><i class=\"fas fa-snowflake me-1\"></i>Iceberg</span> <span class=\"d-block small text-muted mt-1\">Served over the Iceberg REST catalog. Spark, Trino, PyIceberg, DuckDB.</span></label></div><div class=\"col-6\">")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "<label class=\"btn btn-outline-primary w-100 text-start p-3\" for=\"s3tablesBucketFormatIceberg\"><span class=\"d-block fw-semibold\"><i class=\"fas fa-snowflake me-1\"></i>Iceberg</span> <span class=\"d-block small text-muted mt-1\">Served over the Iceberg REST catalog. Spark, Trino, PyIceberg, DuckDB.</span></label></div><div class=\"col-6\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.LancePort > 0 && data.IcebergPort <= 0 {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, " <input type=\"radio\" class=\"btn-check\" name=\"format\" id=\"s3tablesBucketFormatLance\" value=\"LANCE\" checked> ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, " <input type=\"radio\" class=\"btn-check\" name=\"format\" id=\"s3tablesBucketFormatLance\" value=\"LANCE\" checked> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else if data.LancePort > 0 {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "<input type=\"radio\" class=\"btn-check\" name=\"format\" id=\"s3tablesBucketFormatLance\" value=\"LANCE\"> ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "<input type=\"radio\" class=\"btn-check\" name=\"format\" id=\"s3tablesBucketFormatLance\" value=\"LANCE\"> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "<input type=\"radio\" class=\"btn-check\" name=\"format\" id=\"s3tablesBucketFormatLance\" value=\"LANCE\" disabled> ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "<input type=\"radio\" class=\"btn-check\" name=\"format\" id=\"s3tablesBucketFormatLance\" value=\"LANCE\" disabled> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "<label class=\"btn btn-outline-success w-100 text-start p-3\" for=\"s3tablesBucketFormatLance\"><span class=\"d-block fw-semibold\"><i class=\"fas fa-vector-square me-1\"></i>Lance</span> <span class=\"d-block small text-muted mt-1\">Served over the Lance Namespace API. pylance, LanceDB, Ray.</span></label></div></div><div class=\"form-text\" id=\"s3tablesBucketFormatHint\" data-iceberg-port=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "<label class=\"btn btn-outline-success w-100 text-start p-3\" for=\"s3tablesBucketFormatLance\"><span class=\"d-block fw-semibold\"><i class=\"fas fa-vector-square me-1\"></i>Lance</span> <span class=\"d-block small text-muted mt-1\">Served over the Lance Namespace API. pylance, LanceDB, Ray.</span></label></div></div><div class=\"form-text\" id=\"s3tablesBucketFormatHint\" data-iceberg-port=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var33 string
- templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.IcebergPort))
+ var templ_7745c5c3_Var35 string
+ templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.IcebergPort))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 363, Col: 115}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var35)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 348, Col: 115}
+ return templ_7745c5c3_Err
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var33)
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "\" data-lance-port=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "\" data-lance-port=\"")
+ var templ_7745c5c3_Var36 string
+ templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.LancePort))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_buckets.templ`, Line: 363, Col: 169}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var36)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var34 string
- templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.LancePort))
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "\">A bucket holds one format. Tables of the other are refused.</div></div><div class=\"mb-3\"><label for=\"s3tablesBucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"s3tablesBucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option></select><div class=\"form-text\">The S3 identity that owns this table bucket. Non-admin users can only access table buckets they own.</div></div><div class=\"mb-3\"><label for=\"s3tablesBucketTags\" class=\"form-label\">Tags</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesBucketTags\" name=\"tags\" placeholder=\"key1=value1,key2=value2\"><div class=\"form-text\">Optional tags in key=value format.</div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create</button></div></form></div></div></div><div class=\"modal fade\" id=\"deleteS3TablesBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteS3TablesBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteS3TablesBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-warning\"></i>Delete Table Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><p>Are you sure you want to delete the table bucket <strong id=\"deleteS3TablesBucketName\"></strong>?</p></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-danger\" onclick=\"deleteS3TablesBucket()\"><i class=\"fas fa-trash me-1\"></i>Delete</button></div></div></div></div>")
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_buckets.templ`, Line: 348, Col: 169}
+ return templ_7745c5c3_Err
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var34)
+ templ_7745c5c3_Err = PolicyDatalists().Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "\">A bucket holds one format. Tables of the other are refused.</div></div><div class=\"mb-3\"><label for=\"s3tablesBucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"s3tablesBucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option></select><div class=\"form-text\">The S3 identity that owns this table bucket. Non-admin users can only access table buckets they own.</div></div><div class=\"mb-3\"><label for=\"s3tablesBucketTags\" class=\"form-label\">Tags</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesBucketTags\" name=\"tags\" placeholder=\"key1=value1,key2=value2\"><div class=\"form-text\">Optional tags in key=value format.</div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create</button></div></form></div></div></div><div class=\"modal fade\" id=\"deleteS3TablesBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteS3TablesBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteS3TablesBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-warning\"></i>Delete Table Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><p>Are you sure you want to delete the table bucket <strong id=\"deleteS3TablesBucketName\"></strong>?</p></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-danger\" onclick=\"deleteS3TablesBucket()\"><i class=\"fas fa-trash me-1\"></i>Delete</button></div></div></div></div><div class=\"modal fade\" id=\"s3tablesBucketPolicyModal\" tabindex=\"-1\" aria-labelledby=\"s3tablesBucketPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"s3tablesBucketPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Table Bucket Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"s3tablesBucketPolicyForm\"><div class=\"modal-body\"><input type=\"hidden\" id=\"s3tablesBucketPolicyArn\" name=\"bucket_arn\"><div class=\"mb-3\"><label for=\"s3tablesBucketPolicyText\" class=\"form-label\">Policy JSON</label> <textarea class=\"form-control\" id=\"s3tablesBucketPolicyText\" name=\"policy\" rows=\"12\" placeholder=\"{ }\"></textarea></div><div class=\"form-text\">Provide a policy JSON; use Delete Policy to remove the policy.</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-outline-danger\" onclick=\"deleteS3TablesBucketPolicy()\"><i class=\"fas fa-trash me-1\"></i>Delete Policy</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-save me-1\"></i>Save Policy</button></div></form></div></div></div><div class=\"modal fade\" id=\"s3tablesTagsModal\" tabindex=\"-1\" aria-labelledby=\"s3tablesTagsModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"s3tablesTagsModalLabel\"><i class=\"fas fa-tags me-2\"></i>Resource Tags</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"s3tablesTagsForm\"><div class=\"modal-body\"><input type=\"hidden\" id=\"s3tablesTagsResourceArn\" name=\"resource_arn\"><div class=\"mb-3\"><label class=\"form-label\">Existing Tags</label><pre class=\"bg-light p-3 border rounded\" id=\"s3tablesTagsList\">Loading...</pre></div><div class=\"mb-3\"><label for=\"s3tablesTagsInput\" class=\"form-label\">Add or Update Tags</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesTagsInput\" placeholder=\"key1=value1,key2=value2\"></div><div class=\"mb-3\"><label for=\"s3tablesTagsDeleteInput\" class=\"form-label\">Remove Tag Keys</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesTagsDeleteInput\" placeholder=\"key1,key2\"></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-outline-danger\" onclick=\"deleteS3TablesTags()\"><i class=\"fas fa-trash me-1\"></i>Remove Tags</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-save me-1\"></i>Update Tags</button></div></form></div></div></div><script>\n\t\tdocument.addEventListener('DOMContentLoaded', function() {\n\t\t\tinitS3TablesBuckets();\n\t\t});\n\t</script>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "<div class=\"modal fade\" id=\"s3tablesBucketPolicyModal\" tabindex=\"-1\" aria-labelledby=\"s3tablesBucketPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"s3tablesBucketPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Table Bucket Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"s3tablesBucketPolicyForm\"><div class=\"modal-body\"><input type=\"hidden\" id=\"s3tablesBucketPolicyArn\" name=\"bucket_arn\"><ul class=\"nav nav-tabs\" role=\"tablist\"><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link active\" id=\"s3tablesBucketPolicyEditorTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#s3tablesBucketPolicyEditorTab\" role=\"tab\" aria-controls=\"s3tablesBucketPolicyEditorTab\" aria-selected=\"true\">Editor</button></li><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link\" id=\"s3tablesBucketPolicyJsonTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#s3tablesBucketPolicyJsonTab\" role=\"tab\" aria-controls=\"s3tablesBucketPolicyJsonTab\" aria-selected=\"false\">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=\"s3tablesBucketPolicyEditorTab\" role=\"tabpanel\" aria-labelledby=\"s3tablesBucketPolicyEditorTabBtn\"><div id=\"s3tablesBucketPolicyEditorBody\"></div><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"s3tablesBucketPolicyAddStatementBtn\"><i class=\"fas fa-plus me-1\"></i>Add statement</button></div><div class=\"tab-pane fade\" id=\"s3tablesBucketPolicyJsonTab\" role=\"tabpanel\" aria-labelledby=\"s3tablesBucketPolicyJsonTabBtn\"><textarea class=\"form-control\" id=\"s3tablesBucketPolicyText\" name=\"policy\" rows=\"12\" placeholder=\"{ }\"></textarea></div></div><div class=\"form-text\">Provide a policy JSON; use Delete Policy to remove the policy.</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-outline-danger\" onclick=\"deleteS3TablesBucketPolicy()\"><i class=\"fas fa-trash me-1\"></i>Delete Policy</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-save me-1\"></i>Save Policy</button></div></form></div></div></div><div class=\"modal fade\" id=\"s3tablesTagsModal\" tabindex=\"-1\" aria-labelledby=\"s3tablesTagsModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"s3tablesTagsModalLabel\"><i class=\"fas fa-tags me-2\"></i>Resource Tags</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"s3tablesTagsForm\"><div class=\"modal-body\"><input type=\"hidden\" id=\"s3tablesTagsResourceArn\" name=\"resource_arn\"><div class=\"mb-3\"><label class=\"form-label\">Existing Tags</label><pre class=\"bg-light p-3 border rounded\" id=\"s3tablesTagsList\">Loading...</pre></div><div class=\"mb-3\"><label for=\"s3tablesTagsInput\" class=\"form-label\">Add or Update Tags</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesTagsInput\" placeholder=\"key1=value1,key2=value2\"></div><div class=\"mb-3\"><label for=\"s3tablesTagsDeleteInput\" class=\"form-label\">Remove Tag Keys</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesTagsDeleteInput\" placeholder=\"key1,key2\"></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-outline-danger\" onclick=\"deleteS3TablesTags()\"><i class=\"fas fa-trash me-1\"></i>Remove Tags</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-save me-1\"></i>Update Tags</button></div></form></div></div></div><script>\n\t\tdocument.addEventListener('DOMContentLoaded', function() {\n\t\t\tinitS3TablesBuckets();\n\t\t});\n\t</script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
diff --git a/weed/admin/view/app/s3tables_tables.templ b/weed/admin/view/app/s3tables_tables.templ
index 84ce15481b..8df58785db 100644
--- a/weed/admin/view/app/s3tables_tables.templ
+++ b/weed/admin/view/app/s3tables_tables.templ
@@ -254,8 +254,10 @@ templ S3TablesTables(data dash.S3TablesTablesData) {
</div>
</div>
</div>
+ @PolicyDatalists()
+
<div class="modal fade" id="s3tablesTablePolicyModal" tabindex="-1" aria-labelledby="s3tablesTablePolicyModalLabel" 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="s3tablesTablePolicyModalLabel">
@@ -268,9 +270,24 @@ templ S3TablesTables(data dash.S3TablesTablesData) {
<input type="hidden" id="s3tablesTablePolicyBucketArn" name="bucket_arn"/>
<input type="hidden" id="s3tablesTablePolicyNamespace" name="namespace"/>
<input type="hidden" id="s3tablesTablePolicyName" name="name"/>
- <div class="mb-3">
- <label for="s3tablesTablePolicyText" class="form-label">Policy JSON</label>
- <textarea class="form-control" id="s3tablesTablePolicyText" name="policy" rows="12" placeholder="{ }"></textarea>
+ <ul class="nav nav-tabs" role="tablist">
+ <li class="nav-item" role="presentation">
+ <button class="nav-link active" id="s3tablesTablePolicyEditorTabBtn" type="button" data-bs-toggle="tab" data-bs-target="#s3tablesTablePolicyEditorTab" role="tab" aria-controls="s3tablesTablePolicyEditorTab" aria-selected="true">Editor</button>
+ </li>
+ <li class="nav-item" role="presentation">
+ <button class="nav-link" id="s3tablesTablePolicyJsonTabBtn" type="button" data-bs-toggle="tab" data-bs-target="#s3tablesTablePolicyJsonTab" role="tab" aria-controls="s3tablesTablePolicyJsonTab" aria-selected="false">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="s3tablesTablePolicyEditorTab" role="tabpanel" aria-labelledby="s3tablesTablePolicyEditorTabBtn">
+ <div id="s3tablesTablePolicyEditorBody"></div>
+ <button type="button" class="btn btn-sm btn-outline-secondary" id="s3tablesTablePolicyAddStatementBtn">
+ <i class="fas fa-plus me-1"></i>Add statement
+ </button>
+ </div>
+ <div class="tab-pane fade" id="s3tablesTablePolicyJsonTab" role="tabpanel" aria-labelledby="s3tablesTablePolicyJsonTabBtn">
+ <textarea class="form-control" id="s3tablesTablePolicyText" name="policy" rows="12" placeholder="{ }"></textarea>
+ </div>
</div>
</div>
<div class="modal-footer">
diff --git a/weed/admin/view/app/s3tables_tables_templ.go b/weed/admin/view/app/s3tables_tables_templ.go
index 88fe8227e7..e8efb6074d 100644
--- a/weed/admin/view/app/s3tables_tables_templ.go
+++ b/weed/admin/view/app/s3tables_tables_templ.go
@@ -53,7 +53,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.ResolveAttributeValue(templ.CSSClasses(templ_7745c5c3_Var2).String())
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 1, Col: 0}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 1, Col: 0}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
if templ_7745c5c3_Err != nil {
@@ -66,7 +66,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.ResolveAttributeValue(formatBadgeTitle(data.BucketFormat))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 15, Col: 119}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 15, Col: 119}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var4)
if templ_7745c5c3_Err != nil {
@@ -79,7 +79,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(formatLabel(data.BucketFormat))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 15, Col: 154}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 15, Col: 154}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
@@ -98,7 +98,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var6 templ.SafeURL
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/object-store/s3tables/buckets/%s/namespaces", url.PathEscape(bucketName))))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 28, Col: 116}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 28, Col: 116}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
@@ -121,7 +121,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(data.BucketARN)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 36, Col: 60}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 36, Col: 60}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
@@ -134,7 +134,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(data.Namespace)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 37, Col: 59}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 37, Col: 59}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
@@ -157,7 +157,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.ResolveAttributeValue(data.BucketARN)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 42, Col: 67}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 42, Col: 67}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var9)
if templ_7745c5c3_Err != nil {
@@ -170,7 +170,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.ResolveAttributeValue(data.Namespace)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 42, Col: 101}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 42, Col: 101}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var10)
if templ_7745c5c3_Err != nil {
@@ -183,7 +183,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalTables))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 53, Col: 46}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 53, Col: 46}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
if templ_7745c5c3_Err != nil {
@@ -196,7 +196,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var12 string
templ_7745c5c3_Var12, 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/s3tables_tables.templ`, Line: 72, Col: 43}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 72, Col: 43}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
if templ_7745c5c3_Err != nil {
@@ -219,7 +219,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(tableName)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 111, Col: 26}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 111, Col: 26}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil {
@@ -241,7 +241,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.ResolveAttributeValue(templ.CSSClasses(templ_7745c5c3_Var14).String())
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 1, Col: 0}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 1, Col: 0}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var15)
if templ_7745c5c3_Err != nil {
@@ -254,7 +254,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.ResolveAttributeValue(formatBadgeTitle(table.Format))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 113, Col: 97}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 113, Col: 97}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var16)
if templ_7745c5c3_Err != nil {
@@ -267,7 +267,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(formatLabel(table.Format))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 113, Col: 127}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 113, Col: 127}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
@@ -285,7 +285,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(rows)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 117, Col: 61}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 117, Col: 61}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
if templ_7745c5c3_Err != nil {
@@ -308,7 +308,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(table.TableARN)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 122, Col: 56}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 122, Col: 56}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
@@ -321,7 +321,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(table.CreatedAt.Format("2006-01-02 15:04"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 123, Col: 59}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 123, Col: 59}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
@@ -334,7 +334,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(table.ModifiedAt.Format("2006-01-02 15:04"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 124, Col: 60}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 124, Col: 60}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
if templ_7745c5c3_Err != nil {
@@ -352,7 +352,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(bucketName)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 127, Col: 50}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 127, Col: 50}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
if templ_7745c5c3_Err != nil {
@@ -365,7 +365,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(data.Namespace)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 127, Col: 69}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 127, Col: 69}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
if templ_7745c5c3_Err != nil {
@@ -378,7 +378,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(tableName)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 127, Col: 83}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 127, Col: 83}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
if templ_7745c5c3_Err != nil {
@@ -406,7 +406,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(table.MetadataLocation)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 134, Col: 68}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 134, Col: 68}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
if templ_7745c5c3_Err != nil {
@@ -434,7 +434,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var26 templ.SafeURL
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/object-store/s3tables/buckets/%s/namespaces/%s/tables/%s", url.PathEscape(bucketName), url.PathEscape(data.Namespace), url.PathEscape(tableName))))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 142, Col: 238}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 142, Col: 238}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
if templ_7745c5c3_Err != nil {
@@ -457,7 +457,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var27 string
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.ResolveAttributeValue(table.TableARN)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 150, Col: 126}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 150, Col: 126}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var27)
if templ_7745c5c3_Err != nil {
@@ -470,7 +470,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var28 string
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.ResolveAttributeValue(table.TableARN)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 153, Col: 128}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 153, Col: 128}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var28)
if templ_7745c5c3_Err != nil {
@@ -483,7 +483,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var29 string
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.ResolveAttributeValue(tableName)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 153, Col: 158}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 153, Col: 158}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var29)
if templ_7745c5c3_Err != nil {
@@ -496,7 +496,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var30 string
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.ResolveAttributeValue(tableName)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 156, Col: 126}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 156, Col: 126}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var30)
if templ_7745c5c3_Err != nil {
@@ -525,7 +525,7 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
var templ_7745c5c3_Var31 string
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.ResolveAttributeValue(formatLabel(data.BucketFormat))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3tables_tables.templ`, Line: 203, Col: 164}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_tables.templ`, Line: 203, Col: 164}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var31)
if templ_7745c5c3_Err != nil {
@@ -541,7 +541,15 @@ func S3TablesTables(data dash.S3TablesTablesData) templ.Component {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "</div><div class=\"mb-3\"><label for=\"s3tablesTableMetadata\" class=\"form-label\">Metadata JSON (optional)</label> <textarea class=\"form-control\" id=\"s3tablesTableMetadata\" name=\"metadata\" rows=\"6\" placeholder=\"{ }\"></textarea></div><div class=\"mb-3\"><label for=\"s3tablesTableTags\" class=\"form-label\">Tags</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesTableTags\" name=\"tags\" placeholder=\"key1=value1,key2=value2\"></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create</button></div></form></div></div></div><div class=\"modal fade\" id=\"deleteS3TablesTableModal\" tabindex=\"-1\" aria-labelledby=\"deleteS3TablesTableModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteS3TablesTableModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-warning\"></i>Delete Table</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><p>Are you sure you want to delete the table <strong id=\"deleteS3TablesTableName\"></strong>?</p><div class=\"mb-3\"><label for=\"deleteS3TablesTableVersion\" class=\"form-label\">Version Token (optional)</label> <input type=\"text\" class=\"form-control\" id=\"deleteS3TablesTableVersion\" placeholder=\"Version token\"></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-danger\" onclick=\"deleteS3TablesTable()\"><i class=\"fas fa-trash me-1\"></i>Delete</button></div></div></div></div><div class=\"modal fade\" id=\"s3tablesTablePolicyModal\" tabindex=\"-1\" aria-labelledby=\"s3tablesTablePolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"s3tablesTablePolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Table Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"s3tablesTablePolicyForm\"><div class=\"modal-body\"><input type=\"hidden\" id=\"s3tablesTablePolicyBucketArn\" name=\"bucket_arn\"> <input type=\"hidden\" id=\"s3tablesTablePolicyNamespace\" name=\"namespace\"> <input type=\"hidden\" id=\"s3tablesTablePolicyName\" name=\"name\"><div class=\"mb-3\"><label for=\"s3tablesTablePolicyText\" class=\"form-label\">Policy JSON</label> <textarea class=\"form-control\" id=\"s3tablesTablePolicyText\" name=\"policy\" rows=\"12\" placeholder=\"{ }\"></textarea></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-outline-danger\" onclick=\"deleteS3TablesTablePolicy()\"><i class=\"fas fa-trash me-1\"></i>Delete Policy</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-save me-1\"></i>Save Policy</button></div></form></div></div></div><div class=\"modal fade\" id=\"s3tablesTagsModal\" tabindex=\"-1\" aria-labelledby=\"s3tablesTagsModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"s3tablesTagsModalLabel\"><i class=\"fas fa-tags me-2\"></i>Resource Tags</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"s3tablesTagsForm\"><div class=\"modal-body\"><input type=\"hidden\" id=\"s3tablesTagsResourceArn\" name=\"resource_arn\"><div class=\"mb-3\"><label class=\"form-label\">Existing Tags</label><pre class=\"bg-light p-3 border rounded\" id=\"s3tablesTagsList\">Loading...</pre></div><div class=\"mb-3\"><label for=\"s3tablesTagsInput\" class=\"form-label\">Add or Update Tags</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesTagsInput\" placeholder=\"key1=value1,key2=value2\"></div><div class=\"mb-3\"><label for=\"s3tablesTagsDeleteInput\" class=\"form-label\">Remove Tag Keys</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesTagsDeleteInput\" placeholder=\"key1,key2\"></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-outline-danger\" onclick=\"deleteS3TablesTags()\"><i class=\"fas fa-trash me-1\"></i>Remove Tags</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-save me-1\"></i>Update Tags</button></div></form></div></div></div><script>\n\t\tdocument.addEventListener('DOMContentLoaded', function() {\n\t\t\tinitS3TablesTables();\n\t\t});\n\t</script>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "</div><div class=\"mb-3\"><label for=\"s3tablesTableMetadata\" class=\"form-label\">Metadata JSON (optional)</label> <textarea class=\"form-control\" id=\"s3tablesTableMetadata\" name=\"metadata\" rows=\"6\" placeholder=\"{ }\"></textarea></div><div class=\"mb-3\"><label for=\"s3tablesTableTags\" class=\"form-label\">Tags</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesTableTags\" name=\"tags\" placeholder=\"key1=value1,key2=value2\"></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create</button></div></form></div></div></div><div class=\"modal fade\" id=\"deleteS3TablesTableModal\" tabindex=\"-1\" aria-labelledby=\"deleteS3TablesTableModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteS3TablesTableModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-warning\"></i>Delete Table</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><p>Are you sure you want to delete the table <strong id=\"deleteS3TablesTableName\"></strong>?</p><div class=\"mb-3\"><label for=\"deleteS3TablesTableVersion\" class=\"form-label\">Version Token (optional)</label> <input type=\"text\" class=\"form-control\" id=\"deleteS3TablesTableVersion\" placeholder=\"Version token\"></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-danger\" onclick=\"deleteS3TablesTable()\"><i class=\"fas fa-trash me-1\"></i>Delete</button></div></div></div></div>")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = PolicyDatalists().Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "<div class=\"modal fade\" id=\"s3tablesTablePolicyModal\" tabindex=\"-1\" aria-labelledby=\"s3tablesTablePolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"s3tablesTablePolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Table Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"s3tablesTablePolicyForm\"><div class=\"modal-body\"><input type=\"hidden\" id=\"s3tablesTablePolicyBucketArn\" name=\"bucket_arn\"> <input type=\"hidden\" id=\"s3tablesTablePolicyNamespace\" name=\"namespace\"> <input type=\"hidden\" id=\"s3tablesTablePolicyName\" name=\"name\"><ul class=\"nav nav-tabs\" role=\"tablist\"><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link active\" id=\"s3tablesTablePolicyEditorTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#s3tablesTablePolicyEditorTab\" role=\"tab\" aria-controls=\"s3tablesTablePolicyEditorTab\" aria-selected=\"true\">Editor</button></li><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link\" id=\"s3tablesTablePolicyJsonTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#s3tablesTablePolicyJsonTab\" role=\"tab\" aria-controls=\"s3tablesTablePolicyJsonTab\" aria-selected=\"false\">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=\"s3tablesTablePolicyEditorTab\" role=\"tabpanel\" aria-labelledby=\"s3tablesTablePolicyEditorTabBtn\"><div id=\"s3tablesTablePolicyEditorBody\"></div><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"s3tablesTablePolicyAddStatementBtn\"><i class=\"fas fa-plus me-1\"></i>Add statement</button></div><div class=\"tab-pane fade\" id=\"s3tablesTablePolicyJsonTab\" role=\"tabpanel\" aria-labelledby=\"s3tablesTablePolicyJsonTabBtn\"><textarea class=\"form-control\" id=\"s3tablesTablePolicyText\" name=\"policy\" rows=\"12\" placeholder=\"{ }\"></textarea></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-outline-danger\" onclick=\"deleteS3TablesTablePolicy()\"><i class=\"fas fa-trash me-1\"></i>Delete Policy</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-save me-1\"></i>Save Policy</button></div></form></div></div></div><div class=\"modal fade\" id=\"s3tablesTagsModal\" tabindex=\"-1\" aria-labelledby=\"s3tablesTagsModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"s3tablesTagsModalLabel\"><i class=\"fas fa-tags me-2\"></i>Resource Tags</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"s3tablesTagsForm\"><div class=\"modal-body\"><input type=\"hidden\" id=\"s3tablesTagsResourceArn\" name=\"resource_arn\"><div class=\"mb-3\"><label class=\"form-label\">Existing Tags</label><pre class=\"bg-light p-3 border rounded\" id=\"s3tablesTagsList\">Loading...</pre></div><div class=\"mb-3\"><label for=\"s3tablesTagsInput\" class=\"form-label\">Add or Update Tags</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesTagsInput\" placeholder=\"key1=value1,key2=value2\"></div><div class=\"mb-3\"><label for=\"s3tablesTagsDeleteInput\" class=\"form-label\">Remove Tag Keys</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesTagsDeleteInput\" placeholder=\"key1,key2\"></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-outline-danger\" onclick=\"deleteS3TablesTags()\"><i class=\"fas fa-trash me-1\"></i>Remove Tags</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-save me-1\"></i>Update Tags</button></div></form></div></div></div><script>\n\t\tdocument.addEventListener('DOMContentLoaded', function() {\n\t\t\tinitS3TablesTables();\n\t\t});\n\t</script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
diff --git a/weed/admin/view/layout/layout.templ b/weed/admin/view/layout/layout.templ
index 9733919deb..09fc8f0cf5 100644
--- a/weed/admin/view/layout/layout.templ
+++ b/weed/admin/view/layout/layout.templ
@@ -370,6 +370,7 @@ templ Layout(view ViewContext, content templ.Component) {
<script src={ string(view.P("/static/js/admin.js")) }></script>
<script src={ string(view.P("/static/js/iam-utils.js")) }></script>
<script src={ string(view.P("/static/js/s3tables.js")) }></script>
+ <script src={ string(view.P("/static/js/policy_editor.js")) }></script>
</body>
</html>
}
diff --git a/weed/admin/view/layout/layout_templ.go b/weed/admin/view/layout/layout_templ.go
index 5c7fa667fe..bd1ad4cf89 100644
--- a/weed/admin/view/layout/layout_templ.go
+++ b/weed/admin/view/layout/layout_templ.go
@@ -85,7 +85,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.ResolveAttributeValue(csrfToken)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 55, Col: 47}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 55, Col: 47}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
if templ_7745c5c3_Err != nil {
@@ -98,7 +98,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var3 templ.SafeURL
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinURLErrs(string(view.P("/static/favicon.ico")))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 56, Col: 65}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 56, Col: 65}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
@@ -111,7 +111,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var4 templ.SafeURL
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinURLErrs(string(view.P("/static/css/bootstrap.min.css")))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 59, Col: 64}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 59, Col: 64}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
@@ -124,7 +124,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var5 templ.SafeURL
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(string(view.P("/static/css/fontawesome.min.css")))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 61, Col: 66}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 61, Col: 66}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
@@ -137,7 +137,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.ResolveAttributeValue(string(view.P("/static/js/htmx.min.js")))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 63, Col: 58}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 63, Col: 58}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var6)
if templ_7745c5c3_Err != nil {
@@ -150,7 +150,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var7 templ.SafeURL
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinURLErrs(string(view.P("/static/css/admin.css")))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 65, Col: 73}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 65, Col: 73}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
@@ -171,7 +171,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var8 templ.SafeURL
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/admin"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 74, Col: 71}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 74, Col: 71}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
@@ -184,7 +184,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(username)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 90, Col: 73}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 90, Col: 73}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
@@ -197,7 +197,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var10 templ.SafeURL
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/logout"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 93, Col: 85}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 93, Col: 85}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
@@ -210,7 +210,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var11 templ.SafeURL
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/admin"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 112, Col: 71}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 112, Col: 71}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
if templ_7745c5c3_Err != nil {
@@ -232,7 +232,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.ResolveAttributeValue(templ.CSSClasses(templ_7745c5c3_Var12).String())
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 1, Col: 0}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 1, Col: 0}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var13)
if templ_7745c5c3_Err != nil {
@@ -245,7 +245,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%t", isClusterPage))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 117, Col: 207}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 117, Col: 207}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var14)
if templ_7745c5c3_Err != nil {
@@ -267,7 +267,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.ResolveAttributeValue(templ.CSSClasses(templ_7745c5c3_Var15).String())
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 1, Col: 0}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 1, Col: 0}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var16)
if templ_7745c5c3_Err != nil {
@@ -280,7 +280,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var17 templ.SafeURL
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/cluster/masters"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 124, Col: 98}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 124, Col: 98}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
@@ -293,7 +293,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var18 templ.SafeURL
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/cluster/volume-servers"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 129, Col: 105}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 129, Col: 105}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
if templ_7745c5c3_Err != nil {
@@ -306,7 +306,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var19 templ.SafeURL
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/cluster/filers"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 134, Col: 97}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 134, Col: 97}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
@@ -319,7 +319,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var20 templ.SafeURL
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/cluster/s3"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 139, Col: 93}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 139, Col: 93}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
@@ -332,7 +332,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var21 templ.SafeURL
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/cluster/mount-clients"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 144, Col: 104}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 144, Col: 104}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
if templ_7745c5c3_Err != nil {
@@ -354,7 +354,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.ResolveAttributeValue(templ.CSSClasses(templ_7745c5c3_Var22).String())
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 1, Col: 0}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 1, Col: 0}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var23)
if templ_7745c5c3_Err != nil {
@@ -367,7 +367,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%t", isStoragePage))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 152, Col: 207}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 152, Col: 207}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var24)
if templ_7745c5c3_Err != nil {
@@ -389,7 +389,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var26 string
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.ResolveAttributeValue(templ.CSSClasses(templ_7745c5c3_Var25).String())
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 1, Col: 0}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 1, Col: 0}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var26)
if templ_7745c5c3_Err != nil {
@@ -402,7 +402,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var27 templ.SafeURL
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/storage/volumes"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 159, Col: 98}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 159, Col: 98}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
if templ_7745c5c3_Err != nil {
@@ -415,7 +415,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var28 templ.SafeURL
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/storage/ec-shards"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 164, Col: 100}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 164, Col: 100}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
if templ_7745c5c3_Err != nil {
@@ -428,7 +428,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var29 templ.SafeURL
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/storage/collections"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 169, Col: 102}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 169, Col: 102}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
if templ_7745c5c3_Err != nil {
@@ -441,7 +441,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var30 templ.SafeURL
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/object-store/buckets"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 183, Col: 86}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 183, Col: 86}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
if templ_7745c5c3_Err != nil {
@@ -454,7 +454,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var31 templ.SafeURL
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/object-store/s3tables/buckets"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 188, Col: 95}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 188, Col: 95}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
if templ_7745c5c3_Err != nil {
@@ -467,7 +467,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var32 templ.SafeURL
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/object-store/users"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 193, Col: 84}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 193, Col: 84}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
if templ_7745c5c3_Err != nil {
@@ -480,7 +480,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var33 templ.SafeURL
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/object-store/groups"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 198, Col: 85}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 198, Col: 85}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
if templ_7745c5c3_Err != nil {
@@ -493,7 +493,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var34 templ.SafeURL
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/object-store/service-accounts"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 203, Col: 95}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 203, Col: 95}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
if templ_7745c5c3_Err != nil {
@@ -506,7 +506,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var35 templ.SafeURL
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/object-store/policies"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 208, Col: 87}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 208, Col: 87}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
if templ_7745c5c3_Err != nil {
@@ -519,7 +519,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var36 templ.SafeURL
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/files"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 219, Col: 71}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 219, Col: 71}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
if templ_7745c5c3_Err != nil {
@@ -553,7 +553,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var37 templ.SafeURL
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/mq/brokers"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 240, Col: 108}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 240, Col: 108}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
if templ_7745c5c3_Err != nil {
@@ -571,7 +571,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var38 templ.SafeURL
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/mq/brokers"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 244, Col: 101}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 244, Col: 101}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
if templ_7745c5c3_Err != nil {
@@ -594,7 +594,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var39 templ.SafeURL
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/mq/topics"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 251, Col: 107}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 251, Col: 107}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
if templ_7745c5c3_Err != nil {
@@ -612,7 +612,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var40 templ.SafeURL
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/mq/topics"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 255, Col: 100}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 255, Col: 100}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
if templ_7745c5c3_Err != nil {
@@ -635,7 +635,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var41 templ.SafeURL
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/mq/brokers"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 267, Col: 97}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 267, Col: 97}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
if templ_7745c5c3_Err != nil {
@@ -648,7 +648,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var42 templ.SafeURL
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/mq/topics"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 272, Col: 96}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 272, Col: 96}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))
if templ_7745c5c3_Err != nil {
@@ -671,7 +671,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var43 templ.SafeURL
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/plugin/lanes/default"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 289, Col: 97}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 289, Col: 97}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
if templ_7745c5c3_Err != nil {
@@ -689,7 +689,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var44 templ.SafeURL
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/plugin/lanes/default"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 293, Col: 90}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 293, Col: 90}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))
if templ_7745c5c3_Err != nil {
@@ -712,7 +712,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var45 templ.SafeURL
templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/plugin/lanes/lifecycle"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 300, Col: 99}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 300, Col: 99}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var45))
if templ_7745c5c3_Err != nil {
@@ -730,7 +730,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var46 templ.SafeURL
templ_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/plugin/lanes/lifecycle"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 304, Col: 92}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 304, Col: 92}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))
if templ_7745c5c3_Err != nil {
@@ -753,7 +753,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var47 templ.SafeURL
templ_7745c5c3_Var47, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/plugin/lanes/iceberg"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 311, Col: 97}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 311, Col: 97}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var47))
if templ_7745c5c3_Err != nil {
@@ -771,7 +771,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var48 templ.SafeURL
templ_7745c5c3_Var48, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/plugin/lanes/iceberg"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 315, Col: 90}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 315, Col: 90}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var48))
if templ_7745c5c3_Err != nil {
@@ -794,7 +794,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var49 templ.SafeURL
templ_7745c5c3_Var49, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/plugin/lanes/lance"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 322, Col: 95}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 322, Col: 95}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var49))
if templ_7745c5c3_Err != nil {
@@ -812,7 +812,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var50 templ.SafeURL
templ_7745c5c3_Var50, templ_7745c5c3_Err = templ.JoinURLErrs(view.P("/plugin/lanes/lance"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 326, Col: 88}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 326, Col: 88}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var50))
if templ_7745c5c3_Err != nil {
@@ -838,7 +838,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var51 string
templ_7745c5c3_Var51, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", time.Now().Year()))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 351, Col: 60}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 351, Col: 60}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var51))
if templ_7745c5c3_Err != nil {
@@ -851,7 +851,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var52 string
templ_7745c5c3_Var52, templ_7745c5c3_Err = templ.JoinStringErrs(version.VERSION_NUMBER)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 351, Col: 102}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 351, Col: 102}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var52))
if templ_7745c5c3_Err != nil {
@@ -869,7 +869,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var53 string
templ_7745c5c3_Var53, templ_7745c5c3_Err = templ.JoinStringErrs(version.COMMIT)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 353, Col: 55}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 353, Col: 55}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var53))
if templ_7745c5c3_Err != nil {
@@ -893,7 +893,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var54 string
templ_7745c5c3_Var54, templ_7745c5c3_Err = templ.ResolveAttributeValue(string(view.P("/static/js/bootstrap.bundle.min.js")))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 366, Col: 70}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 366, Col: 70}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var54)
if templ_7745c5c3_Err != nil {
@@ -906,7 +906,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var55 string
templ_7745c5c3_Var55, templ_7745c5c3_Err = templ.ResolveAttributeValue(string(view.P("/static/js/modal-alerts.js")))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 368, Col: 62}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 368, Col: 62}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var55)
if templ_7745c5c3_Err != nil {
@@ -919,7 +919,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var56 string
templ_7745c5c3_Var56, templ_7745c5c3_Err = templ.ResolveAttributeValue(string(view.P("/static/js/admin.js")))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 370, Col: 55}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 370, Col: 55}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var56)
if templ_7745c5c3_Err != nil {
@@ -932,7 +932,7 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var57 string
templ_7745c5c3_Var57, templ_7745c5c3_Err = templ.ResolveAttributeValue(string(view.P("/static/js/iam-utils.js")))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 371, Col: 59}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 371, Col: 59}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var57)
if templ_7745c5c3_Err != nil {
@@ -945,13 +945,26 @@ func Layout(view ViewContext, content templ.Component) templ.Component {
var templ_7745c5c3_Var58 string
templ_7745c5c3_Var58, templ_7745c5c3_Err = templ.ResolveAttributeValue(string(view.P("/static/js/s3tables.js")))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 372, Col: 58}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 372, Col: 58}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var58)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "\"></script></body></html>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "\"></script><script src=\"")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var59 string
+ templ_7745c5c3_Var59, templ_7745c5c3_Err = templ.ResolveAttributeValue(string(view.P("/static/js/policy_editor.js")))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 373, Col: 63}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var59)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, "\"></script></body></html>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -975,140 +988,140 @@ func LoginForm(title string, errorMessage string, csrfToken string) templ.Compon
}()
}
ctx = templ.InitializeContext(ctx)
- templ_7745c5c3_Var59 := templ.GetChildren(ctx)
- if templ_7745c5c3_Var59 == nil {
- templ_7745c5c3_Var59 = templ.NopComponent
+ templ_7745c5c3_Var60 := templ.GetChildren(ctx)
+ if templ_7745c5c3_Var60 == nil {
+ templ_7745c5c3_Var60 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
prefix := dash.URLPrefixFromContext(ctx)
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, "<!doctype html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, "<!doctype html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var60 string
- templ_7745c5c3_Var60, templ_7745c5c3_Err = templ.JoinStringErrs(title)
+ var templ_7745c5c3_Var61 string
+ templ_7745c5c3_Var61, templ_7745c5c3_Err = templ.JoinStringErrs(title)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 385, Col: 17}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 386, Col: 17}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var60))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var61))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, " - Login</title><link rel=\"icon\" href=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, " - Login</title><link rel=\"icon\" href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var61 templ.SafeURL
- templ_7745c5c3_Var61, templ_7745c5c3_Err = templ.JoinURLErrs(prefix + "/static/favicon.ico")
+ var templ_7745c5c3_Var62 templ.SafeURL
+ templ_7745c5c3_Var62, templ_7745c5c3_Err = templ.JoinURLErrs(prefix + "/static/favicon.ico")
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 386, Col: 58}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 387, Col: 58}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var61))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var62))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "\" type=\"image/x-icon\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><link href=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, "\" type=\"image/x-icon\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><link href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var62 templ.SafeURL
- templ_7745c5c3_Var62, templ_7745c5c3_Err = templ.JoinURLErrs(prefix + "/static/css/bootstrap.min.css")
+ var templ_7745c5c3_Var63 templ.SafeURL
+ templ_7745c5c3_Var63, templ_7745c5c3_Err = templ.JoinURLErrs(prefix + "/static/css/bootstrap.min.css")
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 388, Col: 57}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 389, Col: 57}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var62))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var63))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, "\" rel=\"stylesheet\"><link href=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "\" rel=\"stylesheet\"><link href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var63 templ.SafeURL
- templ_7745c5c3_Var63, templ_7745c5c3_Err = templ.JoinURLErrs(prefix + "/static/css/fontawesome.min.css")
+ var templ_7745c5c3_Var64 templ.SafeURL
+ templ_7745c5c3_Var64, templ_7745c5c3_Err = templ.JoinURLErrs(prefix + "/static/css/fontawesome.min.css")
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 389, Col: 59}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 390, Col: 59}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var63))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var64))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "\" rel=\"stylesheet\"></head><body class=\"bg-light\"><div class=\"container\"><div class=\"row justify-content-center min-vh-100 align-items-center\"><div class=\"col-md-6 col-lg-4\"><div class=\"card shadow\"><div class=\"card-body p-5\"><div class=\"text-center mb-4\"><i class=\"fas fa-server fa-3x text-primary mb-3\"></i><h4 class=\"card-title\">")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 92, "\" rel=\"stylesheet\"></head><body class=\"bg-light\"><div class=\"container\"><div class=\"row justify-content-center min-vh-100 align-items-center\"><div class=\"col-md-6 col-lg-4\"><div class=\"card shadow\"><div class=\"card-body p-5\"><div class=\"text-center mb-4\"><i class=\"fas fa-server fa-3x text-primary mb-3\"></i><h4 class=\"card-title\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var64 string
- templ_7745c5c3_Var64, templ_7745c5c3_Err = templ.JoinStringErrs(title)
+ var templ_7745c5c3_Var65 string
+ templ_7745c5c3_Var65, templ_7745c5c3_Err = templ.JoinStringErrs(title)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 399, Col: 57}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 400, Col: 57}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var64))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var65))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 92, "</h4><p class=\"text-muted\">Please sign in to continue</p></div>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, "</h4><p class=\"text-muted\">Please sign in to continue</p></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if errorMessage != "" {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, "<div class=\"alert alert-danger\" role=\"alert\"><i class=\"fas fa-exclamation-triangle me-2\"></i> ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 94, "<div class=\"alert alert-danger\" role=\"alert\"><i class=\"fas fa-exclamation-triangle me-2\"></i> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var65 string
- templ_7745c5c3_Var65, templ_7745c5c3_Err = templ.JoinStringErrs(errorMessage)
+ var templ_7745c5c3_Var66 string
+ templ_7745c5c3_Var66, templ_7745c5c3_Err = templ.JoinStringErrs(errorMessage)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 406, Col: 45}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 407, Col: 45}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var65))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var66))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 94, "</div>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 95, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 95, "<form method=\"POST\" action=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 96, "<form method=\"POST\" action=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var66 templ.SafeURL
- templ_7745c5c3_Var66, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(prefix + "/login"))
+ var templ_7745c5c3_Var67 templ.SafeURL
+ templ_7745c5c3_Var67, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(prefix + "/login"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 410, Col: 85}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 411, Col: 85}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var66))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var67))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 96, "\"><input type=\"hidden\" name=\"csrf_token\" value=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 97, "\"><input type=\"hidden\" name=\"csrf_token\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var67 string
- templ_7745c5c3_Var67, templ_7745c5c3_Err = templ.ResolveAttributeValue(csrfToken)
+ var templ_7745c5c3_Var68 string
+ templ_7745c5c3_Var68, templ_7745c5c3_Err = templ.ResolveAttributeValue(csrfToken)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 411, Col: 84}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 412, Col: 84}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var67)
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var68)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 97, "\"><div class=\"mb-3\"><label for=\"username\" class=\"form-label\">Username</label><div class=\"input-group\"><span class=\"input-group-text\"><i class=\"fas fa-user\"></i></span> <input type=\"text\" class=\"form-control\" id=\"username\" name=\"username\" required></div></div><div class=\"mb-4\"><label for=\"password\" class=\"form-label\">Password</label><div class=\"input-group\"><span class=\"input-group-text\"><i class=\"fas fa-lock\"></i></span> <input type=\"password\" class=\"form-control\" id=\"password\" name=\"password\" required></div></div><button type=\"submit\" class=\"btn btn-primary w-100\"><i class=\"fas fa-sign-in-alt me-2\"></i>Sign In</button></form></div></div></div></div></div><script src=\"")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, "\"><div class=\"mb-3\"><label for=\"username\" class=\"form-label\">Username</label><div class=\"input-group\"><span class=\"input-group-text\"><i class=\"fas fa-user\"></i></span> <input type=\"text\" class=\"form-control\" id=\"username\" name=\"username\" required></div></div><div class=\"mb-4\"><label for=\"password\" class=\"form-label\">Password</label><div class=\"input-group\"><span class=\"input-group-text\"><i class=\"fas fa-lock\"></i></span> <input type=\"password\" class=\"form-control\" id=\"password\" name=\"password\" required></div></div><button type=\"submit\" class=\"btn btn-primary w-100\"><i class=\"fas fa-sign-in-alt me-2\"></i>Sign In</button></form></div></div></div></div></div><script src=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var68 string
- templ_7745c5c3_Var68, templ_7745c5c3_Err = templ.ResolveAttributeValue(prefix + "/static/js/bootstrap.bundle.min.js")
+ var templ_7745c5c3_Var69 string
+ templ_7745c5c3_Var69, templ_7745c5c3_Err = templ.ResolveAttributeValue(prefix + "/static/js/bootstrap.bundle.min.js")
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/layout/layout.templ`, Line: 442, Col: 63}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/layout/layout.templ`, Line: 443, Col: 63}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var68)
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var69)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, "\"></script></body></html>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 99, "\"></script></body></html>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
diff --git a/weed/s3api/policy_engine/bucket_policy.go b/weed/s3api/policy_engine/bucket_policy.go
new file mode 100644
index 0000000000..b7cf969c92
--- /dev/null
+++ b/weed/s3api/policy_engine/bucket_policy.go
@@ -0,0 +1,86 @@
+package policy_engine
+
+import (
+ "fmt"
+ "strings"
+)
+
+// ValidateBucketPolicy performs bucket-specific policy validation, on top of
+// the generic structural checks in ValidatePolicy. It enforces the rules
+// that make a policy document valid as an S3 *bucket* policy specifically:
+// every statement must name a Principal, and every Resource/NotResource/Action
+// must scope to the given bucket.
+//
+// This is shared between the S3 gateway's PutBucketPolicy handler
+// (weed/s3api/s3api_bucket_policy_handlers.go) and the admin UI
+// (weed/admin/dash) so both enforce identical rules.
+func ValidateBucketPolicy(policyDoc *PolicyDocument, bucket string) error {
+ if policyDoc.Version != PolicyVersion2012_10_17 {
+ return fmt.Errorf("unsupported policy version: %s (must be %s)", policyDoc.Version, PolicyVersion2012_10_17)
+ }
+
+ if len(policyDoc.Statement) == 0 {
+ return fmt.Errorf("policy document must contain at least one statement")
+ }
+
+ for i, statement := range policyDoc.Statement {
+ // Bucket policies must have Principal
+ if statement.Principal == nil {
+ return fmt.Errorf("statement %d: bucket policies must specify a Principal", i)
+ }
+
+ // Validate resources refer to this bucket
+ for _, resource := range statement.Resource.Strings() {
+ if !ResourceMatchesBucket(resource, bucket) {
+ return fmt.Errorf("statement %d: resource %s does not match bucket %s", i, resource, bucket)
+ }
+ }
+
+ // Validate NotResources refer to this bucket
+ if statement.NotResource != nil {
+ for _, notResource := range statement.NotResource.Strings() {
+ if !ResourceMatchesBucket(notResource, bucket) {
+ return fmt.Errorf("statement %d: NotResource %s does not match bucket %s", i, notResource, bucket)
+ }
+ }
+ }
+
+ // Validate actions are S3 actions
+ for _, action := range statement.Action.Strings() {
+ if !strings.HasPrefix(action, "s3:") {
+ return fmt.Errorf("statement %d: bucket policies only support S3 actions, got %s", i, action)
+ }
+ }
+ }
+
+ return nil
+}
+
+// ResourceMatchesBucket checks if a resource ARN is valid for the given bucket.
+func ResourceMatchesBucket(resource, bucket string) bool {
+ // Accepted formats for S3 bucket policies:
+ // AWS-style ARNs (standard):
+ // arn:aws:s3:::bucket-name
+ // arn:aws:s3:::bucket-name/*
+ // arn:aws:s3:::bucket-name/path/to/object
+ // Simplified formats (for convenience):
+ // bucket-name
+ // bucket-name/*
+ // bucket-name/path/to/object
+
+ var resourcePath string
+ const awsPrefix = "arn:aws:s3:::"
+
+ // Strip the optional ARN prefix to get the resource path
+ if path, ok := strings.CutPrefix(resource, awsPrefix); ok {
+ resourcePath = path
+ } else {
+ resourcePath = resource
+ }
+
+ // After stripping the optional ARN prefix, the resource path must
+ // either match the bucket name exactly, or be a path within the bucket.
+ return resourcePath == bucket ||
+ resourcePath == bucket+"/*" ||
+ strings.HasPrefix(resourcePath, bucket+"/")
+}
diff --git a/weed/s3api/policy_engine/bucket_policy_test.go b/weed/s3api/policy_engine/bucket_policy_test.go
new file mode 100644
index 0000000000..217e1c8fab
--- /dev/null
+++ b/weed/s3api/policy_engine/bucket_policy_test.go
@@ -0,0 +1,106 @@
+package policy_engine
+
+import "testing"
+
+func TestResourceMatchesBucket(t *testing.T) {
+ tests := []struct {
+ name string
+ resource string
+ bucket string
+ want bool
+ }{
+ {"bare bucket name", "my-bucket", "my-bucket", true},
+ {"bare wildcard", "my-bucket/*", "my-bucket", true},
+ {"bare object key", "my-bucket/path/to/key", "my-bucket", true},
+ {"arn bucket", "arn:aws:s3:::my-bucket", "my-bucket", true},
+ {"arn wildcard", "arn:aws:s3:::my-bucket/*", "my-bucket", true},
+ {"arn object key", "arn:aws:s3:::my-bucket/path/to/key", "my-bucket", true},
+ {"wrong bucket", "other-bucket", "my-bucket", false},
+ {"wrong bucket arn", "arn:aws:s3:::other-bucket/*", "my-bucket", false},
+ {"prefix collision", "my-bucket2", "my-bucket", false},
+ {"prefix collision arn", "arn:aws:s3:::my-bucket2/*", "my-bucket", false},
+ {"empty resource", "", "my-bucket", false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := ResourceMatchesBucket(tt.resource, tt.bucket); got != tt.want {
+ t.Errorf("ResourceMatchesBucket(%q, %q) = %v, want %v", tt.resource, tt.bucket, got, tt.want)
+ }
+ })
+ }
+}
+
+func simpleAwsPrincipal() *PolicyPrincipal {
+ return NewPolicyPrincipalPtr("*")
+}
+
+func TestValidateBucketPolicy(t *testing.T) {
+ bucket := "my-bucket"
+
+ validStatement := func() PolicyStatement {
+ return PolicyStatement{
+ Effect: PolicyEffectAllow,
+ Principal: simpleAwsPrincipal(),
+ Action: NewStringOrStringSlice("s3:GetObject"),
+ Resource: NewStringOrStringSlicePtr("arn:aws:s3:::" + bucket + "/*"),
+ }
+ }
+
+ t.Run("valid policy", func(t *testing.T) {
+ doc := &PolicyDocument{Version: PolicyVersion2012_10_17, Statement: []PolicyStatement{validStatement()}}
+ if err := ValidateBucketPolicy(doc, bucket); err != nil {
+ t.Errorf("expected no error, got %v", err)
+ }
+ })
+
+ t.Run("bad version", func(t *testing.T) {
+ doc := &PolicyDocument{Version: "2008-10-17", Statement: []PolicyStatement{validStatement()}}
+ if err := ValidateBucketPolicy(doc, bucket); err == nil {
+ t.Error("expected error for bad version")
+ }
+ })
+
+ t.Run("zero statements", func(t *testing.T) {
+ doc := &PolicyDocument{Version: PolicyVersion2012_10_17, Statement: []PolicyStatement{}}
+ if err := ValidateBucketPolicy(doc, bucket); err == nil {
+ t.Error("expected error for zero statements")
+ }
+ })
+
+ t.Run("missing principal", func(t *testing.T) {
+ stmt := validStatement()
+ stmt.Principal = nil
+ doc := &PolicyDocument{Version: PolicyVersion2012_10_17, Statement: []PolicyStatement{stmt}}
+ if err := ValidateBucketPolicy(doc, bucket); err == nil {
+ t.Error("expected error for missing principal")
+ }
+ })
+
+ t.Run("foreign resource", func(t *testing.T) {
+ stmt := validStatement()
+ stmt.Resource = NewStringOrStringSlicePtr("arn:aws:s3:::other-bucket/*")
+ doc := &PolicyDocument{Version: PolicyVersion2012_10_17, Statement: []PolicyStatement{stmt}}
+ if err := ValidateBucketPolicy(doc, bucket); err == nil {
+ t.Error("expected error for foreign resource")
+ }
+ })
+
+ t.Run("foreign not-resource", func(t *testing.T) {
+ stmt := validStatement()
+ stmt.Resource = nil
+ stmt.NotResource = NewStringOrStringSlicePtr("arn:aws:s3:::other-bucket/*")
+ doc := &PolicyDocument{Version: PolicyVersion2012_10_17, Statement: []PolicyStatement{stmt}}
+ if err := ValidateBucketPolicy(doc, bucket); err == nil {
+ t.Error("expected error for foreign NotResource")
+ }
+ })
+
+ t.Run("non-s3 action", func(t *testing.T) {
+ stmt := validStatement()
+ stmt.Action = NewStringOrStringSlice("iam:CreateUser")
+ doc := &PolicyDocument{Version: PolicyVersion2012_10_17, Statement: []PolicyStatement{stmt}}
+ if err := ValidateBucketPolicy(doc, bucket); err == nil {
+ t.Error("expected error for non-s3 action")
+ }
+ })
+}
diff --git a/weed/s3api/s3api_bucket_policy_handlers.go b/weed/s3api/s3api_bucket_policy_handlers.go
index f8cdea1535..9e38fe09f5 100644
--- a/weed/s3api/s3api_bucket_policy_handlers.go
+++ b/weed/s3api/s3api_bucket_policy_handlers.go
@@ -7,7 +7,6 @@ import (
"fmt"
"io"
"net/http"
- "strings"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
@@ -16,7 +15,10 @@ import (
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
)
-// Bucket policy metadata key for storing policies in filer
+// Bucket policy metadata key for storing policies in filer.
+// Also consumed directly by weed/admin/dash for the admin UI's bucket
+// policy management, so keep it exported and don't change its value
+// without updating that package too.
const BUCKET_POLICY_METADATA_KEY = "s3-bucket-policy"
// Sentinel errors for bucket policy operations
@@ -97,7 +99,7 @@ func (s3a *S3ApiServer) PutBucketPolicyHandler(w http.ResponseWriter, r *http.Re
}
// Additional bucket policy specific validation
- if err := s3a.validateBucketPolicy(&policyDoc, bucket); err != nil {
+ if err := policy_engine.ValidateBucketPolicy(&policyDoc, bucket); err != nil {
glog.Errorf("Bucket policy validation failed: %v", err)
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidPolicyDocument)
return
@@ -293,78 +295,6 @@ func (s3a *S3ApiServer) deleteBucketPolicy(bucket string) error {
})
}
-// validateBucketPolicy performs bucket-specific policy validation
-func (s3a *S3ApiServer) validateBucketPolicy(policyDoc *policy_engine.PolicyDocument, bucket string) error {
- if policyDoc.Version != "2012-10-17" {
- return fmt.Errorf("unsupported policy version: %s (must be 2012-10-17)", policyDoc.Version)
- }
-
- if len(policyDoc.Statement) == 0 {
- return fmt.Errorf("policy document must contain at least one statement")
- }
-
- for i, statement := range policyDoc.Statement {
- // Bucket policies must have Principal
- if statement.Principal == nil {
- return fmt.Errorf("statement %d: bucket policies must specify a Principal", i)
- }
-
- // Validate resources refer to this bucket
- for _, resource := range statement.Resource.Strings() {
- if !s3a.validateResourceForBucket(resource, bucket) {
- return fmt.Errorf("statement %d: resource %s does not match bucket %s", i, resource, bucket)
- }
- }
-
- // Validate NotResources refer to this bucket
- if statement.NotResource != nil {
- for _, notResource := range statement.NotResource.Strings() {
- if !s3a.validateResourceForBucket(notResource, bucket) {
- return fmt.Errorf("statement %d: NotResource %s does not match bucket %s", i, notResource, bucket)
- }
- }
- }
-
- // Validate actions are S3 actions
- for _, action := range statement.Action.Strings() {
- if !strings.HasPrefix(action, "s3:") {
- return fmt.Errorf("statement %d: bucket policies only support S3 actions, got %s", i, action)
- }
- }
- }
-
- return nil
-}
-
-// validateResourceForBucket checks if a resource ARN is valid for the given bucket
-func (s3a *S3ApiServer) validateResourceForBucket(resource, bucket string) bool {
- // Accepted formats for S3 bucket policies:
- // AWS-style ARNs (standard):
- // arn:aws:s3:::bucket-name
- // arn:aws:s3:::bucket-name/*
- // arn:aws:s3:::bucket-name/path/to/object
- // Simplified formats (for convenience):
- // bucket-name
- // bucket-name/*
- // bucket-name/path/to/object
-
- var resourcePath string
- const awsPrefix = "arn:aws:s3:::"
-
- // Strip the optional ARN prefix to get the resource path
- if path, ok := strings.CutPrefix(resource, awsPrefix); ok {
- resourcePath = path
- } else {
- resourcePath = resource
- }
-
- // After stripping the optional ARN prefix, the resource path must
- // either match the bucket name exactly, or be a path within the bucket.
- return resourcePath == bucket ||
- resourcePath == bucket+"/*" ||
- strings.HasPrefix(resourcePath, bucket+"/")
-}
-
// IAM integration functions
// updateBucketPolicyInIAM updates the IAM system with the new bucket policy