Prepare verified laboratory 6 implementation and evidence

This commit is contained in:
rey
2026-11-17 17:32:06 +03:00
parent 470d9d6f1e
commit 7d56e52fd0
335 changed files with 31206 additions and 72 deletions
@@ -0,0 +1,86 @@
package storage
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/signer"
"io"
"net/http"
"net/url"
"os"
"time"
)
type Config struct{ Endpoint, Access, Secret, Bucket string }
func ReadConfig(path string) (Config, error) {
var c Config
b, e := os.ReadFile(path)
if e != nil {
return c, fmt.Errorf("S3 credentials unavailable")
}
if e = json.Unmarshal(b, &c); e != nil {
return c, fmt.Errorf("invalid S3 credentials format")
}
if c.Endpoint == "" || c.Access == "" || c.Secret == "" || c.Bucket == "" {
return c, fmt.Errorf("incomplete S3 configuration")
}
return c, nil
}
func FromConfig(c Config) (*S3, error) { return New(c.Endpoint, c.Access, c.Secret, c.Bucket) }
// RustFS provides S3 SDKs, but its documented administrative API is separate.
// Use the SDK's SigV4 signer; do not implement signing or persist credentials in command arguments.
func admin(ctx context.Context, c Config, path string, body []byte) error {
r, e := http.NewRequestWithContext(ctx, http.MethodPut, "http://"+c.Endpoint+"/rustfs/admin/v3/"+path, bytes.NewReader(body))
if e != nil {
return e
}
sum := sha256.Sum256(body)
r.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum[:]))
r.Header.Set("Content-Type", "application/json")
signed := signer.SignV4(*r, c.Access, c.Secret, "", "us-east-1")
response, e := (&http.Client{Timeout: 5 * time.Second}).Do(signed)
if e != nil {
return fmt.Errorf("S3 admin transport failed")
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 64*1024))
if response.StatusCode != 200 && response.StatusCode != 204 {
return fmt.Errorf("S3 admin operation rejected: HTTP %d", response.StatusCode)
}
return nil
}
func Bootstrap(ctx context.Context, root, app Config) error {
s, e := FromConfig(root)
if e != nil {
return e
}
exists, e := s.Client.BucketExists(ctx, root.Bucket)
if e != nil {
return fmt.Errorf("bucket availability check failed")
}
if !exists {
if e = s.Client.MakeBucket(ctx, root.Bucket, minio.MakeBucketOptions{Region: "us-east-1"}); e != nil {
return fmt.Errorf("bucket creation failed")
}
}
policy := map[string]any{"Version": "2012-10-17", "Statement": []any{
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetBucketLocation", "s3:ListBucket"}, "Resource": []string{"arn:aws:s3:::" + app.Bucket}},
map[string]any{"Effect": "Allow", "Action": []string{"s3:PutObject", "s3:GetObject", "s3:DeleteObject"}, "Resource": []string{"arn:aws:s3:::" + app.Bucket + "/originals/*", "arn:aws:s3:::" + app.Bucket + "/staging/*", "arn:aws:s3:::" + app.Bucket + "/variants/*"}},
}}
raw, _ := json.Marshal(policy)
if e = admin(ctx, root, "add-canned-policy?name=messenger", raw); e != nil {
return e
}
raw, _ = json.Marshal(map[string]string{"secretKey": app.Secret, "status": "enabled"})
if e = admin(ctx, root, "add-user?accessKey="+url.QueryEscape(app.Access), raw); e != nil {
return e
}
return admin(ctx, root, "set-user-or-group-policy?policyName=messenger&userOrGroup="+url.QueryEscape(app.Access)+"&isGroup=false", nil)
}
@@ -0,0 +1,21 @@
package storage
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestMissingBucketFailsReadiness(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) }))
defer server.Close()
store, err := New(strings.TrimPrefix(server.URL, "http://"), "synthetic-access", "synthetic-secret", "missing")
if err != nil {
t.Fatal(err)
}
if err = store.Ready(context.Background()); err == nil {
t.Fatal("missing bucket reported ready")
}
}
+81
View File
@@ -0,0 +1,81 @@
package storage
import (
"backend/internal/domain/model"
"backend/internal/domain/port"
"context"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"io"
"net"
"net/http"
"time"
)
type S3 struct {
Client *minio.Client
Bucket string
}
func New(endpoint, access, secret, bucket string) (*S3, error) {
client, err := minio.New(endpoint, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: false, Region: "us-east-1", Transport: &http.Transport{DialContext: (&net.Dialer{Timeout: time.Second}).DialContext, ResponseHeaderTimeout: 3 * time.Second, MaxIdleConnsPerHost: 8}})
if err != nil {
return nil, err
}
return &S3{client, bucket}, nil
}
func mapError(err error) error {
if err == nil {
return nil
}
r := minio.ToErrorResponse(err)
if r.Code == "NoSuchKey" || r.Code == "NoSuchObject" || r.Code == "NotFound" {
return model.ErrNotFound
}
return model.ErrUnavailable
}
func (s *S3) Put(ctx context.Context, key string, r io.Reader, size int64, mime string) error {
_, err := s.Client.PutObject(ctx, s.Bucket, key, r, size, minio.PutObjectOptions{ContentType: mime, DisableMultipart: true})
return mapError(err)
}
func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, error) {
obj, err := s.Client.GetObject(ctx, s.Bucket, key, minio.GetObjectOptions{})
if err != nil {
return nil, mapError(err)
}
if _, err = obj.Stat(); err != nil {
_ = obj.Close()
return nil, mapError(err)
}
return obj, nil
}
func (s *S3) Stat(ctx context.Context, key string) (port.Object, error) {
r, e := s.Client.StatObject(ctx, s.Bucket, key, minio.StatObjectOptions{})
return port.Object{Key: key, ETag: r.ETag, Size: r.Size, Modified: r.LastModified.UTC().Truncate(time.Second)}, mapError(e)
}
func (s *S3) Remove(ctx context.Context, key string) error {
return mapError(s.Client.RemoveObject(ctx, s.Bucket, key, minio.RemoveObjectOptions{}))
}
func (s *S3) List(ctx context.Context, after string) ([]port.Object, bool, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
out := []port.Object{}
for r := range s.Client.ListObjects(ctx, s.Bucket, minio.ListObjectsOptions{Prefix: "originals/", StartAfter: after, Recursive: true, MaxKeys: 100}) {
if r.Err != nil {
return nil, false, mapError(r.Err)
}
// HTTP Last-Modified has second precision; RustFS inventory also carries milliseconds.
out = append(out, port.Object{Key: r.Key, ETag: r.ETag, Size: r.Size, Modified: r.LastModified.UTC().Truncate(time.Second)})
if len(out) > 100 {
return out[:100], true, nil
}
}
return out, false, nil
}
func (s *S3) Ready(ctx context.Context) error {
exists, err := s.Client.BucketExists(ctx, s.Bucket)
if err != nil || !exists {
return model.ErrUnavailable
}
return nil
}