mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f3b225052 | ||
|
|
e2b602c486 | ||
|
|
4081940720 | ||
|
|
9318a1265e | ||
|
|
5725d2c464 |
No files matched your search
@@ -54,9 +54,9 @@ Table of Contents
|
||||
=================
|
||||
|
||||
* [Quick Start](#quick-start)
|
||||
* [Quick Start with weed mini](#quick-start-with-weed-mini)
|
||||
* [Quick Start for S3 API on Docker](#quick-start-for-s3-api-on-docker)
|
||||
* [Quick Start with Single Binary](#quick-start-with-single-binary)
|
||||
* [Quick Start SeaweedFS S3 on AWS](#quick-start-seaweedfs-s3-on-aws)
|
||||
* [Introduction](#introduction)
|
||||
* [Features](#features)
|
||||
* [Additional Features](#additional-features)
|
||||
@@ -78,32 +78,6 @@ Table of Contents
|
||||
|
||||
# Quick Start #
|
||||
|
||||
|
||||
## Quick Start with weed mini ##
|
||||
The easiest way to get started with SeaweedFS for development and testing:
|
||||
|
||||
* Download the latest binary from https://github.com/seaweedfs/seaweedfs/releases and unzip a single binary file `weed` or `weed.exe`.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
# remove quarantine on macOS
|
||||
# xattr -d com.apple.quarantine ./weed
|
||||
export AWS_ACCESS_KEY_ID=admin
|
||||
export AWS_SECRET_ACCESS_KEY=key
|
||||
./weed mini -dir=/data
|
||||
```
|
||||
|
||||
This single command starts a complete SeaweedFS setup with:
|
||||
- **Master UI**: http://localhost:9333
|
||||
- **Volume Server**: http://localhost:9340
|
||||
- **Filer UI**: http://localhost:8888
|
||||
- **S3 Endpoint**: http://localhost:8333
|
||||
- **WebDAV**: http://localhost:7333
|
||||
- **Admin UI**: http://localhost:23646
|
||||
|
||||
Perfect for development, testing, learning SeaweedFS, and single node deployments!
|
||||
|
||||
## Quick Start for S3 API on Docker ##
|
||||
|
||||
`docker run -p 8333:8333 chrislusf/seaweedfs server -s3`
|
||||
@@ -111,10 +85,13 @@ Perfect for development, testing, learning SeaweedFS, and single node deployment
|
||||
## Quick Start with Single Binary ##
|
||||
* Download the latest binary from https://github.com/seaweedfs/seaweedfs/releases and unzip a single binary file `weed` or `weed.exe`. Or run `go install github.com/seaweedfs/seaweedfs/weed@latest`.
|
||||
* `export AWS_ACCESS_KEY_ID=admin ; export AWS_SECRET_ACCESS_KEY=key` as the admin credentials to access the object store.
|
||||
* Run `weed server -dir=/some/data/dir -s3` to start one master, one volume server, one filer, and one S3 gateway. The difference with `weed mini` is that `weed mini` can auto configure based on the single host environment, while `weed server` requires manual configuration and are designed for production use.
|
||||
* Run `weed server -dir=/some/data/dir -s3` to start one master, one volume server, one filer, and one S3 gateway.
|
||||
|
||||
Also, to increase capacity, just add more volume servers by running `weed volume -dir="/some/data/dir2" -master="<master_host>:9333" -port=8081` locally, or on a different machine, or on thousands of machines. That is it!
|
||||
|
||||
## Quick Start SeaweedFS S3 on AWS ##
|
||||
* Setup fast production-ready [SeaweedFS S3 on AWS with cloudformation](https://aws.amazon.com/marketplace/pp/prodview-nzelz5gprlrjc)
|
||||
|
||||
# Introduction #
|
||||
|
||||
SeaweedFS is a simple and highly scalable distributed file system. There are two objectives:
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
# Server-Side Encryption with Customer-Provided Keys (SSE-C) Implementation
|
||||
|
||||
This document describes the implementation of SSE-C support in SeaweedFS, addressing the feature request from [GitHub Discussion #5361](https://github.com/seaweedfs/seaweedfs/discussions/5361).
|
||||
|
||||
## Overview
|
||||
|
||||
SSE-C allows clients to provide their own encryption keys for server-side encryption of objects stored in SeaweedFS. The server encrypts the data using the customer-provided AES-256 key but does not store the key itself - only an MD5 hash of the key for validation purposes.
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### Architecture
|
||||
|
||||
The SSE-C implementation follows a transparent encryption/decryption pattern:
|
||||
|
||||
1. **Upload (PUT/POST)**: Data is encrypted with the customer key before being stored
|
||||
2. **Download (GET/HEAD)**: Encrypted data is decrypted on-the-fly using the customer key
|
||||
3. **Metadata Storage**: Only the encryption algorithm and key MD5 are stored as metadata
|
||||
|
||||
### Key Components
|
||||
|
||||
#### 1. Constants and Headers (`weed/s3api/s3_constants/header.go`)
|
||||
- Added AWS-compatible SSE-C header constants
|
||||
- Support for both regular and copy-source SSE-C headers
|
||||
|
||||
#### 2. Core SSE-C Logic (`weed/s3api/s3_sse_c.go`)
|
||||
- **SSECustomerKey**: Structure to hold customer encryption key and metadata
|
||||
- **SSECEncryptedReader**: Streaming encryption with AES-256-CTR mode
|
||||
- **SSECDecryptedReader**: Streaming decryption with IV extraction
|
||||
- **validateAndParseSSECHeaders**: Shared validation logic (DRY principle)
|
||||
- **ParseSSECHeaders**: Parse regular SSE-C headers
|
||||
- **ParseSSECCopySourceHeaders**: Parse copy-source SSE-C headers
|
||||
- Header validation and parsing functions
|
||||
- Metadata extraction and response handling
|
||||
|
||||
#### 3. Error Handling (`weed/s3api/s3err/s3api_errors.go`)
|
||||
- New error codes for SSE-C validation failures
|
||||
- AWS-compatible error messages and HTTP status codes
|
||||
|
||||
#### 4. S3 API Integration
|
||||
- **PUT Object Handler**: Encrypts data streams transparently
|
||||
- **GET Object Handler**: Decrypts data streams transparently
|
||||
- **HEAD Object Handler**: Validates keys and returns appropriate headers
|
||||
- **Metadata Storage**: Integrates with existing `SaveAmzMetaData` function
|
||||
|
||||
### Encryption Scheme
|
||||
|
||||
- **Algorithm**: AES-256-CTR (Counter mode)
|
||||
- **Key Size**: 256 bits (32 bytes)
|
||||
- **IV Generation**: Random 16-byte IV per object
|
||||
- **Storage Format**: `[IV][EncryptedData]` where IV is prepended to encrypted content
|
||||
|
||||
### Metadata Storage
|
||||
|
||||
SSE-C metadata is stored in the filer's extended attributes:
|
||||
```
|
||||
x-amz-server-side-encryption-customer-algorithm: "AES256"
|
||||
x-amz-server-side-encryption-customer-key-md5: "<md5-hash-of-key>"
|
||||
```
|
||||
|
||||
## API Compatibility
|
||||
|
||||
### Required Headers for Encryption (PUT/POST)
|
||||
```
|
||||
x-amz-server-side-encryption-customer-algorithm: AES256
|
||||
x-amz-server-side-encryption-customer-key: <base64-encoded-256-bit-key>
|
||||
x-amz-server-side-encryption-customer-key-md5: <md5-hash-of-key>
|
||||
```
|
||||
|
||||
### Required Headers for Decryption (GET/HEAD)
|
||||
Same headers as encryption - the server validates the key MD5 matches.
|
||||
|
||||
### Copy Operations
|
||||
Support for copy-source SSE-C headers:
|
||||
```
|
||||
x-amz-copy-source-server-side-encryption-customer-algorithm
|
||||
x-amz-copy-source-server-side-encryption-customer-key
|
||||
x-amz-copy-source-server-side-encryption-customer-key-md5
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The implementation provides AWS-compatible error responses:
|
||||
|
||||
- **InvalidEncryptionAlgorithmError**: Non-AES256 algorithm specified
|
||||
- **InvalidArgument**: Invalid key format, size, or MD5 mismatch
|
||||
- **Missing customer key**: Object encrypted but no key provided
|
||||
- **Unnecessary customer key**: Object not encrypted but key provided
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **Key Management**: Customer keys are never stored - only MD5 hashes for validation
|
||||
2. **IV Randomness**: Fresh random IV generated for each object
|
||||
3. **Transparent Security**: Volume servers never see unencrypted data
|
||||
4. **Key Validation**: Strict validation of key format, size, and MD5
|
||||
|
||||
## Testing
|
||||
|
||||
Comprehensive test suite covers:
|
||||
- Header validation and parsing (regular and copy-source)
|
||||
- Encryption/decryption round-trip
|
||||
- Error condition handling
|
||||
- Metadata extraction
|
||||
- Code reuse validation (DRY principle)
|
||||
- AWS S3 compatibility
|
||||
|
||||
Run tests with:
|
||||
```bash
|
||||
go test -v ./weed/s3api
|
||||
|
||||
## Usage Example
|
||||
|
||||
### Upload with SSE-C
|
||||
```bash
|
||||
# Generate a 256-bit key
|
||||
KEY=$(openssl rand -base64 32)
|
||||
KEY_MD5=$(echo -n "$KEY" | base64 -d | openssl dgst -md5 -binary | base64)
|
||||
|
||||
# Upload object with SSE-C
|
||||
curl -X PUT "http://localhost:8333/bucket/object" \
|
||||
-H "x-amz-server-side-encryption-customer-algorithm: AES256" \
|
||||
-H "x-amz-server-side-encryption-customer-key: $KEY" \
|
||||
-H "x-amz-server-side-encryption-customer-key-md5: $KEY_MD5" \
|
||||
--data-binary @file.txt
|
||||
```
|
||||
|
||||
### Download with SSE-C
|
||||
```bash
|
||||
# Download object with SSE-C (same key required)
|
||||
curl "http://localhost:8333/bucket/object" \
|
||||
-H "x-amz-server-side-encryption-customer-algorithm: AES256" \
|
||||
-H "x-amz-server-side-encryption-customer-key: $KEY" \
|
||||
-H "x-amz-server-side-encryption-customer-key-md5: $KEY_MD5"
|
||||
```
|
||||
|
||||
## Integration Points
|
||||
|
||||
### Existing SeaweedFS Features
|
||||
- **Filer Metadata**: Extends existing metadata storage
|
||||
- **Volume Servers**: No changes required - store encrypted data transparently
|
||||
- **S3 API**: Integrates seamlessly with existing handlers
|
||||
- **Versioning**: Compatible with object versioning
|
||||
- **Multipart Upload**: Ready for multipart upload integration
|
||||
|
||||
### Future Enhancements
|
||||
- **SSE-S3**: Server-managed encryption keys
|
||||
- **SSE-KMS**: External key management service integration
|
||||
- **Performance Optimization**: Hardware acceleration for encryption
|
||||
- **Compliance**: Enhanced audit logging for encrypted objects
|
||||
|
||||
## File Changes Summary
|
||||
|
||||
1. **`weed/s3api/s3_constants/header.go`** - Added SSE-C header constants
|
||||
2. **`weed/s3api/s3_sse_c.go`** - Core SSE-C implementation (NEW)
|
||||
3. **`weed/s3api/s3_sse_c_test.go`** - Comprehensive test suite (NEW)
|
||||
4. **`weed/s3api/s3err/s3api_errors.go`** - Added SSE-C error codes
|
||||
5. **`weed/s3api/s3api_object_handlers.go`** - GET/HEAD with SSE-C support
|
||||
6. **`weed/s3api/s3api_object_handlers_put.go`** - PUT with SSE-C support
|
||||
7. **`weed/server/filer_server_handlers_write_autochunk.go`** - Metadata storage
|
||||
|
||||
## Compliance
|
||||
|
||||
This implementation follows the [AWS S3 SSE-C specification](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ServerSideEncryptionCustomerKeys.html) for maximum compatibility with existing S3 clients and tools.
|
||||
|
||||
## Performance Impact
|
||||
|
||||
- **Encryption Overhead**: Minimal CPU impact with efficient AES-CTR streaming
|
||||
- **Memory Usage**: Constant memory usage via streaming encryption/decryption
|
||||
- **Storage Overhead**: 16 bytes per object for IV storage
|
||||
- **Network**: No additional network overhead
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.05"
|
||||
appVersion: "4.04"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.0.405
|
||||
version: 4.0.404
|
||||
@@ -25,6 +25,12 @@ spec:
|
||||
port: {{ .Values.admin.grpcPort }}
|
||||
targetPort: {{ .Values.admin.grpcPort }}
|
||||
protocol: TCP
|
||||
{{- if .Values.admin.metricsPort }}
|
||||
- name: "metrics"
|
||||
port: {{ .Values.admin.metricsPort }}
|
||||
targetPort: {{ .Values.admin.metricsPort }}
|
||||
protocol: TCP
|
||||
{{- end }}
|
||||
selector:
|
||||
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{{- if .Values.admin.enabled }}
|
||||
{{- if .Values.admin.metricsPort }}
|
||||
{{- if .Values.global.monitoring.enabled }}
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: ServiceMonitor
|
||||
@@ -21,7 +22,7 @@ metadata:
|
||||
spec:
|
||||
endpoints:
|
||||
- interval: 30s
|
||||
port: http
|
||||
port: metrics
|
||||
scrapeTimeout: 5s
|
||||
selector:
|
||||
matchLabels:
|
||||
@@ -29,3 +30,4 @@ spec:
|
||||
app.kubernetes.io/component: admin
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -213,6 +213,10 @@ spec:
|
||||
name: http
|
||||
- containerPort: {{ .Values.admin.grpcPort }}
|
||||
name: grpc
|
||||
{{- if .Values.admin.metricsPort }}
|
||||
- containerPort: {{ .Values.admin.metricsPort }}
|
||||
name: metrics
|
||||
{{- end }}
|
||||
{{- if .Values.admin.readinessProbe.enabled }}
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
|
||||
@@ -4,13 +4,6 @@
|
||||
{{- /* Determine service name based on deployment mode */}}
|
||||
{{- $serviceName := ternary (printf "%s-all-in-one" (include "seaweedfs.name" .)) (printf "%s-s3" (include "seaweedfs.name" .)) .Values.allInOne.enabled }}
|
||||
{{- $s3Port := .Values.allInOne.s3.port | default .Values.s3.port }}
|
||||
{{- /* Build hosts list - support both legacy .host (string) and new .hosts (array) for backwards compatibility */}}
|
||||
{{- $hosts := list }}
|
||||
{{- if kindIs "slice" .Values.s3.ingress.host }}
|
||||
{{- $hosts = .Values.s3.ingress.host }}
|
||||
{{- else if .Values.s3.ingress.host }}
|
||||
{{- $hosts = list .Values.s3.ingress.host }}
|
||||
{{- end }}
|
||||
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
apiVersion: networking.k8s.io/v1
|
||||
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
@@ -37,25 +30,6 @@ spec:
|
||||
tls:
|
||||
{{ .Values.s3.ingress.tls | default list | toYaml | nindent 6}}
|
||||
rules:
|
||||
{{- if $hosts }}
|
||||
{{- range $hosts }}
|
||||
- host: {{ . | quote }}
|
||||
http:
|
||||
paths:
|
||||
- path: {{ $.Values.s3.ingress.path | quote }}
|
||||
pathType: {{ $.Values.s3.ingress.pathType | quote }}
|
||||
backend:
|
||||
{{- if semverCompare ">=1.19-0" $.Capabilities.KubeVersion.GitVersion }}
|
||||
service:
|
||||
name: {{ $serviceName }}
|
||||
port:
|
||||
number: {{ $s3Port }}
|
||||
{{- else }}
|
||||
serviceName: {{ $serviceName }}
|
||||
servicePort: {{ $s3Port }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- else }}
|
||||
- http:
|
||||
paths:
|
||||
- path: {{ .Values.s3.ingress.path | quote }}
|
||||
@@ -70,5 +44,7 @@ spec:
|
||||
serviceName: {{ $serviceName }}
|
||||
servicePort: {{ $s3Port }}
|
||||
{{- end }}
|
||||
{{- if .Values.s3.ingress.host }}
|
||||
host: {{ .Values.s3.ingress.host | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -134,7 +134,7 @@ spec:
|
||||
{{- if .Values.worker.adminServer }}
|
||||
-admin={{ .Values.worker.adminServer }} \
|
||||
{{- else }}
|
||||
-admin={{ template "seaweedfs.name" . }}-admin.{{ .Release.Namespace }}:{{ .Values.admin.port }}{{ if .Values.admin.grpcPort }}.{{ .Values.admin.grpcPort }}{{ end }} \
|
||||
-admin={{ template "seaweedfs.name" . }}-admin.{{ .Release.Namespace }}:{{ .Values.admin.port }} \
|
||||
{{- end }}
|
||||
-capabilities={{ .Values.worker.capabilities }} \
|
||||
-maxConcurrent={{ .Values.worker.maxConcurrent }} \
|
||||
|
||||
@@ -1012,7 +1012,7 @@ s3:
|
||||
ingress:
|
||||
enabled: false
|
||||
className: ""
|
||||
# host: false for "*" hostname, or an array for multiple hostnames
|
||||
# host: false for "*" hostname
|
||||
host: "seaweedfs.cluster.local"
|
||||
path: "/"
|
||||
pathType: Prefix
|
||||
@@ -1099,6 +1099,7 @@ admin:
|
||||
replicas: 1
|
||||
port: 23646 # Default admin port
|
||||
grpcPort: 33646 # Default gRPC port for worker connections
|
||||
metricsPort: 9327
|
||||
loggingOverrideLevel: null
|
||||
|
||||
# Admin authentication
|
||||
@@ -1230,9 +1231,9 @@ worker:
|
||||
metricsPort: 9327
|
||||
|
||||
# Admin server to connect to
|
||||
# Format: "host:port" or auto-discover from admin service
|
||||
adminServer: ""
|
||||
|
||||
|
||||
# Worker capabilities - comma-separated list
|
||||
# Available: vacuum, balance, erasure_coding
|
||||
# Default: "vacuum,balance,erasure_coding" (all capabilities)
|
||||
|
||||
@@ -225,11 +225,11 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
glog.Infof("Worker %s connection closed: %v", workerID, ctx.Err())
|
||||
s.unregisterWorker(conn)
|
||||
s.unregisterWorker(workerID)
|
||||
return nil
|
||||
case <-connCtx.Done():
|
||||
glog.Infof("Worker %s connection cancelled", workerID)
|
||||
s.unregisterWorker(conn)
|
||||
s.unregisterWorker(workerID)
|
||||
return nil
|
||||
default:
|
||||
}
|
||||
@@ -241,7 +241,7 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
|
||||
} else {
|
||||
glog.Errorf("Error receiving from worker %s: %v", workerID, err)
|
||||
}
|
||||
s.unregisterWorker(conn)
|
||||
s.unregisterWorker(workerID)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -294,7 +294,7 @@ func (s *WorkerGrpcServer) handleWorkerMessage(conn *WorkerConnection, msg *work
|
||||
|
||||
case *worker_pb.WorkerMessage_Shutdown:
|
||||
glog.Infof("Worker %s shutting down: %s", workerID, m.Shutdown.Reason)
|
||||
s.unregisterWorker(conn)
|
||||
s.unregisterWorker(workerID)
|
||||
|
||||
default:
|
||||
glog.Warningf("Unknown message type from worker %s", workerID)
|
||||
@@ -463,24 +463,17 @@ func (s *WorkerGrpcServer) safeCloseOutgoingChannel(conn *WorkerConnection, sour
|
||||
}
|
||||
|
||||
// unregisterWorker removes a worker connection
|
||||
func (s *WorkerGrpcServer) unregisterWorker(conn *WorkerConnection) {
|
||||
func (s *WorkerGrpcServer) unregisterWorker(workerID string) {
|
||||
s.connMutex.Lock()
|
||||
existingConn, exists := s.connections[conn.workerID]
|
||||
conn, exists := s.connections[workerID]
|
||||
if !exists {
|
||||
s.connMutex.Unlock()
|
||||
glog.V(2).Infof("unregisterWorker: worker %s not found in connections map (already unregistered)", conn.workerID)
|
||||
return
|
||||
}
|
||||
|
||||
// Only remove if it matches the specific connection instance
|
||||
if existingConn != conn {
|
||||
s.connMutex.Unlock()
|
||||
glog.V(1).Infof("unregisterWorker: worker %s connection replaced, skipping unregister for old connection", conn.workerID)
|
||||
glog.V(2).Infof("unregisterWorker: worker %s not found in connections map (already unregistered)", workerID)
|
||||
return
|
||||
}
|
||||
|
||||
// Remove from map first to prevent duplicate cleanup attempts
|
||||
delete(s.connections, conn.workerID)
|
||||
delete(s.connections, workerID)
|
||||
s.connMutex.Unlock()
|
||||
|
||||
// Cancel context to signal goroutines to stop
|
||||
@@ -489,7 +482,7 @@ func (s *WorkerGrpcServer) unregisterWorker(conn *WorkerConnection) {
|
||||
// Safely close the outgoing channel with recover to handle potential double-close
|
||||
s.safeCloseOutgoingChannel(conn, "unregisterWorker")
|
||||
|
||||
glog.V(1).Infof("Unregistered worker %s", conn.workerID)
|
||||
glog.V(1).Infof("Unregistered worker %s", workerID)
|
||||
}
|
||||
|
||||
// cleanupRoutine periodically cleans up stale connections
|
||||
@@ -512,18 +505,15 @@ func (s *WorkerGrpcServer) cleanupStaleConnections() {
|
||||
cutoff := time.Now().Add(-2 * time.Minute)
|
||||
|
||||
s.connMutex.Lock()
|
||||
// collect connections to remove first to avoid deadlock if unregisterWorker locks
|
||||
var toRemove []*WorkerConnection
|
||||
for _, conn := range s.connections {
|
||||
if conn.lastSeen.Before(cutoff) {
|
||||
toRemove = append(toRemove, conn)
|
||||
}
|
||||
}
|
||||
s.connMutex.Unlock()
|
||||
defer s.connMutex.Unlock()
|
||||
|
||||
for _, conn := range toRemove {
|
||||
glog.Warningf("Cleaning up stale worker connection: %s", conn.workerID)
|
||||
s.unregisterWorker(conn)
|
||||
for workerID, conn := range s.connections {
|
||||
if conn.lastSeen.Before(cutoff) {
|
||||
glog.Warningf("Cleaning up stale worker connection: %s", workerID)
|
||||
conn.cancel()
|
||||
s.safeCloseOutgoingChannel(conn, "cleanupStaleConnections")
|
||||
delete(s.connections, workerID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -224,36 +224,6 @@ func runFuse(cmd *Command, args []string) bool {
|
||||
fusermountPath = parameter.value
|
||||
case "config_dir":
|
||||
util.ConfigurationFileDirectory.Set(parameter.value)
|
||||
// FUSE performance options
|
||||
case "writebackCache":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
mountOptions.writebackCache = &parsed
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "failed to parse 'writebackCache' value %q: %v\n", parameter.value, err)
|
||||
return false
|
||||
}
|
||||
case "asyncDio":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
mountOptions.asyncDio = &parsed
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "failed to parse 'asyncDio' value %q: %v\n", parameter.value, err)
|
||||
return false
|
||||
}
|
||||
case "cacheSymlink":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
mountOptions.cacheSymlink = &parsed
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "failed to parse 'cacheSymlink' value %q: %v\n", parameter.value, err)
|
||||
return false
|
||||
}
|
||||
// macOS-specific FUSE options
|
||||
case "sys.novncache":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
mountOptions.novncache = &parsed
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "failed to parse 'sys.novncache' value %q: %v\n", parameter.value, err)
|
||||
return false
|
||||
}
|
||||
default:
|
||||
t := parameter.name
|
||||
if parameter.value != "true" {
|
||||
|
||||
@@ -47,14 +47,6 @@ type MountOptions struct {
|
||||
rdmaReadOnly *bool
|
||||
rdmaMaxConcurrent *int
|
||||
rdmaTimeoutMs *int
|
||||
|
||||
// FUSE performance options
|
||||
writebackCache *bool
|
||||
asyncDio *bool
|
||||
cacheSymlink *bool
|
||||
|
||||
// macOS-specific FUSE options
|
||||
novncache *bool
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -110,14 +102,6 @@ func init() {
|
||||
mountCpuProfile = cmdMount.Flag.String("cpuprofile", "", "cpu profile output file")
|
||||
mountMemProfile = cmdMount.Flag.String("memprofile", "", "memory profile output file")
|
||||
mountReadRetryTime = cmdMount.Flag.Duration("readRetryTime", 6*time.Second, "maximum read retry wait time")
|
||||
|
||||
// FUSE performance options
|
||||
mountOptions.writebackCache = cmdMount.Flag.Bool("writebackCache", false, "enable FUSE writeback cache for improved write performance (at risk of data loss on crash)")
|
||||
mountOptions.asyncDio = cmdMount.Flag.Bool("asyncDio", false, "enable async direct I/O for better concurrency")
|
||||
mountOptions.cacheSymlink = cmdMount.Flag.Bool("cacheSymlink", false, "enable symlink caching to reduce metadata lookups")
|
||||
|
||||
// macOS-specific FUSE options
|
||||
mountOptions.novncache = cmdMount.Flag.Bool("sys.novncache", false, "(macOS only) disable vnode name caching to avoid stale data")
|
||||
}
|
||||
|
||||
var cmdMount = &Command{
|
||||
|
||||
+29
-41
@@ -208,24 +208,12 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
if runtime.GOARCH == "amd64" {
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "noapplexattr")
|
||||
}
|
||||
if option.novncache != nil && *option.novncache {
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "novncache")
|
||||
}
|
||||
// fuseMountOptions.Options = append(fuseMountOptions.Options, "novncache") // need to test effectiveness
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "slow_statfs")
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "volname="+serverFriendlyName)
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, fmt.Sprintf("iosize=%d", ioSizeMB*1024*1024))
|
||||
}
|
||||
|
||||
if option.writebackCache != nil && *option.writebackCache {
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "writeback_cache")
|
||||
}
|
||||
if option.asyncDio != nil && *option.asyncDio {
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "async_dio")
|
||||
}
|
||||
if option.cacheSymlink != nil && *option.cacheSymlink {
|
||||
fuseMountOptions.EnableSymlinkCaching = true
|
||||
}
|
||||
|
||||
// find mount point
|
||||
mountRoot := filerMountRootPath
|
||||
if mountRoot != "/" && strings.HasSuffix(mountRoot, "/") {
|
||||
@@ -238,34 +226,34 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
}
|
||||
|
||||
seaweedFileSystem := mount.NewSeaweedFileSystem(&mount.Option{
|
||||
MountDirectory: dir,
|
||||
FilerAddresses: filerAddresses,
|
||||
GrpcDialOption: grpcDialOption,
|
||||
FilerMountRootPath: mountRoot,
|
||||
Collection: *option.collection,
|
||||
Replication: *option.replication,
|
||||
TtlSec: int32(*option.ttlSec),
|
||||
DiskType: types.ToDiskType(*option.diskType),
|
||||
ChunkSizeLimit: int64(chunkSizeLimitMB) * 1024 * 1024,
|
||||
ConcurrentWriters: *option.concurrentWriters,
|
||||
ConcurrentReaders: *option.concurrentReaders,
|
||||
CacheDirForRead: *option.cacheDirForRead,
|
||||
CacheSizeMBForRead: *option.cacheSizeMBForRead,
|
||||
CacheDirForWrite: cacheDirForWrite,
|
||||
CacheMetaTTlSec: *option.cacheMetaTtlSec,
|
||||
DataCenter: *option.dataCenter,
|
||||
Quota: int64(*option.collectionQuota) * 1024 * 1024,
|
||||
MountUid: uid,
|
||||
MountGid: gid,
|
||||
MountMode: mountMode,
|
||||
MountCtime: fileInfo.ModTime(),
|
||||
MountMtime: time.Now(),
|
||||
Umask: umask,
|
||||
VolumeServerAccess: *mountOptions.volumeServerAccess,
|
||||
Cipher: cipher,
|
||||
UidGidMapper: uidGidMapper,
|
||||
DisableXAttr: *option.disableXAttr,
|
||||
IsMacOs: runtime.GOOS == "darwin",
|
||||
MountDirectory: dir,
|
||||
FilerAddresses: filerAddresses,
|
||||
GrpcDialOption: grpcDialOption,
|
||||
FilerMountRootPath: mountRoot,
|
||||
Collection: *option.collection,
|
||||
Replication: *option.replication,
|
||||
TtlSec: int32(*option.ttlSec),
|
||||
DiskType: types.ToDiskType(*option.diskType),
|
||||
ChunkSizeLimit: int64(chunkSizeLimitMB) * 1024 * 1024,
|
||||
ConcurrentWriters: *option.concurrentWriters,
|
||||
ConcurrentReaders: *option.concurrentReaders,
|
||||
CacheDirForRead: *option.cacheDirForRead,
|
||||
CacheSizeMBForRead: *option.cacheSizeMBForRead,
|
||||
CacheDirForWrite: cacheDirForWrite,
|
||||
CacheMetaTTlSec: *option.cacheMetaTtlSec,
|
||||
DataCenter: *option.dataCenter,
|
||||
Quota: int64(*option.collectionQuota) * 1024 * 1024,
|
||||
MountUid: uid,
|
||||
MountGid: gid,
|
||||
MountMode: mountMode,
|
||||
MountCtime: fileInfo.ModTime(),
|
||||
MountMtime: time.Now(),
|
||||
Umask: umask,
|
||||
VolumeServerAccess: *mountOptions.volumeServerAccess,
|
||||
Cipher: cipher,
|
||||
UidGidMapper: uidGidMapper,
|
||||
DisableXAttr: *option.disableXAttr,
|
||||
IsMacOs: runtime.GOOS == "darwin",
|
||||
MetadataFlushSeconds: *option.metadataFlushSeconds,
|
||||
// RDMA acceleration options
|
||||
RdmaEnabled: *option.rdmaEnabled,
|
||||
|
||||
@@ -23,7 +23,6 @@ import (
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding"
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
|
||||
|
||||
// TODO: Implement additional task packages (add to default capabilities when ready):
|
||||
// _ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/remote" - for uploading volumes to remote/cloud storage
|
||||
// _ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/replication" - for fixing replication issues and maintaining data consistency
|
||||
|
||||
@@ -55,7 +55,6 @@ func (f *Filer) assignAndUpload(targetFile string, data []byte) (*operation.Assi
|
||||
Count: 1,
|
||||
Collection: util.Nvl(f.metaLogCollection, rule.Collection),
|
||||
Replication: util.Nvl(f.metaLogReplication, rule.Replication),
|
||||
DiskType: rule.DiskType,
|
||||
WritableVolumeCount: rule.VolumeGrowthCount,
|
||||
}
|
||||
|
||||
|
||||
@@ -5,16 +5,12 @@ import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rsa"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -62,13 +58,6 @@ type OIDCConfig struct {
|
||||
|
||||
// JWKSCacheTTLSeconds sets how long to cache JWKS before refresh (default 3600 seconds)
|
||||
JWKSCacheTTLSeconds int `json:"jwksCacheTTLSeconds,omitempty"`
|
||||
|
||||
// TLSCACert is the path to the CA certificate file for custom/self-signed certificates
|
||||
TLSCACert string `json:"tlsCaCert,omitempty"`
|
||||
|
||||
// TLSInsecureSkipVerify controls whether to skip TLS verification.
|
||||
// WARNING: Should only be used in development/testing environments. Never use in production.
|
||||
TLSInsecureSkipVerify bool `json:"tlsInsecureSkipVerify,omitempty"`
|
||||
}
|
||||
|
||||
// JWKS represents JSON Web Key Set
|
||||
@@ -135,45 +124,6 @@ func (p *OIDCProvider) Initialize(config interface{}) error {
|
||||
p.jwksTTL = time.Hour
|
||||
}
|
||||
|
||||
// Configure HTTP client with TLS settings
|
||||
tlsConfig := &tls.Config{
|
||||
InsecureSkipVerify: oidcConfig.TLSInsecureSkipVerify,
|
||||
MinVersion: tls.VersionTLS12, // Prevent TLS downgrade attacks
|
||||
}
|
||||
|
||||
if oidcConfig.TLSInsecureSkipVerify {
|
||||
glog.Warningf("OIDC provider %q is configured to skip TLS verification. This is insecure and should not be used in production.", p.name)
|
||||
}
|
||||
|
||||
if oidcConfig.TLSCACert != "" {
|
||||
// Validate that the CA cert path is absolute to prevent reading unintended files
|
||||
if !filepath.IsAbs(oidcConfig.TLSCACert) {
|
||||
return fmt.Errorf("TLSCACert must be an absolute path, got: %s", oidcConfig.TLSCACert)
|
||||
}
|
||||
|
||||
caCert, err := os.ReadFile(oidcConfig.TLSCACert)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read CA cert file: %w", err)
|
||||
}
|
||||
// Start with the system cert pool to trust public CAs, then add the custom one.
|
||||
rootCAs, _ := x509.SystemCertPool()
|
||||
if rootCAs == nil {
|
||||
rootCAs = x509.NewCertPool()
|
||||
}
|
||||
if !rootCAs.AppendCertsFromPEM(caCert) {
|
||||
return fmt.Errorf("failed to append CA cert from file: %s", oidcConfig.TLSCACert)
|
||||
}
|
||||
tlsConfig.RootCAs = rootCAs
|
||||
}
|
||||
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: tlsConfig,
|
||||
}
|
||||
p.httpClient = &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Transport: transport,
|
||||
}
|
||||
|
||||
// For testing, we'll skip the actual OIDC client initialization
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -49,10 +49,8 @@ const (
|
||||
ConfigFieldClientSecret = "clientSecret"
|
||||
ConfigFieldJWKSUri = "jwksUri"
|
||||
ConfigFieldScopes = "scopes"
|
||||
ConfigFieldUserInfoUri = "userInfoUri"
|
||||
ConfigFieldRedirectUri = "redirectUri"
|
||||
ConfigFieldTLSCACert = "tlsCaCert"
|
||||
ConfigFieldTLSInsecureSkipVerify = "tlsInsecureSkipVerify"
|
||||
ConfigFieldUserInfoUri = "userInfoUri"
|
||||
ConfigFieldRedirectUri = "redirectUri"
|
||||
)
|
||||
|
||||
// Error Messages
|
||||
|
||||
@@ -115,14 +115,6 @@ func (f *ProviderFactory) convertToOIDCConfig(configMap map[string]interface{})
|
||||
config.Scopes = scopes
|
||||
}
|
||||
|
||||
if tlsCaCert, ok := configMap[ConfigFieldTLSCACert].(string); ok {
|
||||
config.TLSCACert = tlsCaCert
|
||||
}
|
||||
|
||||
if tlsInsecureSkipVerify, ok := configMap[ConfigFieldTLSInsecureSkipVerify].(bool); ok {
|
||||
config.TLSInsecureSkipVerify = tlsInsecureSkipVerify
|
||||
}
|
||||
|
||||
// Convert claims mapping
|
||||
if claimsMapInterface, ok := configMap["claimsMapping"]; ok {
|
||||
claimsMap, err := f.convertToStringMap(claimsMapInterface)
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
package sts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
// defaultCredentialGenerator is a reusable instance for generating temporary credentials
|
||||
// Reusing a single instance across all calls to ToSessionInfo() reduces allocation overhead
|
||||
// since this method may be called frequently during signature verification
|
||||
var defaultCredentialGenerator = NewCredentialGenerator()
|
||||
|
||||
// STSSessionClaims represents comprehensive session information embedded in JWT tokens
|
||||
// This eliminates the need for separate session storage by embedding all session
|
||||
// metadata directly in the token itself - enabling true stateless operation
|
||||
@@ -70,17 +63,6 @@ func (c *STSSessionClaims) ToSessionInfo() *SessionInfo {
|
||||
expiresAt = c.ExpiresAt.Time
|
||||
}
|
||||
|
||||
// Generate temporary credentials from the session ID
|
||||
// This is deterministic based on the session ID, so the same credentials are regenerated
|
||||
credentials, err := defaultCredentialGenerator.GenerateTemporaryCredentials(c.SessionId, expiresAt)
|
||||
if err != nil {
|
||||
// Log the error with context - credential generation failure is important for debugging
|
||||
errMsg := fmt.Errorf("generate temporary credentials for session %s: %w", c.SessionId, err)
|
||||
glog.Warningf("Failed to generate credentials for STS session: %v", errMsg)
|
||||
// Return session info without credentials - validation will catch this as invalid
|
||||
credentials = nil
|
||||
}
|
||||
|
||||
return &SessionInfo{
|
||||
SessionId: c.SessionId,
|
||||
SessionName: c.SessionName,
|
||||
@@ -93,7 +75,6 @@ func (c *STSSessionClaims) ToSessionInfo() *SessionInfo {
|
||||
ExternalUserId: c.ExternalUserId,
|
||||
ProviderIssuer: c.ProviderIssuer,
|
||||
RequestContext: c.RequestContext,
|
||||
Credentials: credentials,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,282 +0,0 @@
|
||||
package sts
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestSTSSessionClaimsToSessionInfo tests the ToSessionInfo conversion
|
||||
func TestSTSSessionClaimsToSessionInfo(t *testing.T) {
|
||||
sessionId := "test-session-123"
|
||||
issuer := "test-issuer"
|
||||
expiresAt := time.Now().Add(time.Hour)
|
||||
|
||||
claims := NewSTSSessionClaims(sessionId, issuer, expiresAt).
|
||||
WithSessionName("test-session-name").
|
||||
WithRoleInfo(
|
||||
"arn:aws:iam::123456789012:role/test-role",
|
||||
"arn:aws:iam::123456789012:assumed-role/test-role/session",
|
||||
"arn:aws:iam::123456789012:assumed-role/test-role/session",
|
||||
).
|
||||
WithIdentityProvider("oidc", "user-123", "https://issuer.example.com").
|
||||
WithMaxDuration(time.Hour)
|
||||
|
||||
sessionInfo := claims.ToSessionInfo()
|
||||
|
||||
// Verify basic claims are converted
|
||||
assert.Equal(t, sessionId, sessionInfo.SessionId)
|
||||
assert.Equal(t, "test-session-name", sessionInfo.SessionName)
|
||||
assert.Equal(t, "arn:aws:iam::123456789012:role/test-role", sessionInfo.RoleArn)
|
||||
assert.Equal(t, "arn:aws:iam::123456789012:assumed-role/test-role/session", sessionInfo.AssumedRoleUser)
|
||||
assert.Equal(t, "oidc", sessionInfo.IdentityProvider)
|
||||
assert.Equal(t, "user-123", sessionInfo.ExternalUserId)
|
||||
|
||||
// Verify credentials are generated
|
||||
assert.NotNil(t, sessionInfo.Credentials, "credentials should be populated")
|
||||
assert.NotEmpty(t, sessionInfo.Credentials.AccessKeyId, "access key should be generated")
|
||||
assert.NotEmpty(t, sessionInfo.Credentials.SecretAccessKey, "secret key should be generated")
|
||||
// Credential expiration may have sub-second differences, so just check they're close
|
||||
assert.True(t, sessionInfo.Credentials.Expiration.Sub(expiresAt) < time.Second, "credential expiration should match session expiration")
|
||||
|
||||
// Verify expiration is preserved (within 1 second tolerance for timing differences)
|
||||
assert.WithinDuration(t, expiresAt, sessionInfo.ExpiresAt, 1*time.Second)
|
||||
}
|
||||
|
||||
// TestSTSSessionClaimsToSessionInfoCredentialGeneration tests that credentials are deterministically generated for access key and session token
|
||||
func TestSTSSessionClaimsToSessionInfoCredentialGeneration(t *testing.T) {
|
||||
sessionId := "deterministic-session-id"
|
||||
issuer := "test-issuer"
|
||||
expiresAt := time.Now().Add(time.Hour).Truncate(time.Second)
|
||||
|
||||
claims1 := NewSTSSessionClaims(sessionId, issuer, expiresAt)
|
||||
sessionInfo1 := claims1.ToSessionInfo()
|
||||
|
||||
// Create another claims object with the same session ID and expiration
|
||||
claims2 := NewSTSSessionClaims(sessionId, issuer, expiresAt)
|
||||
sessionInfo2 := claims2.ToSessionInfo()
|
||||
|
||||
// Verify that both have valid credentials
|
||||
assert.NotNil(t, sessionInfo1.Credentials, "credentials should be populated")
|
||||
assert.NotNil(t, sessionInfo2.Credentials, "credentials should be populated")
|
||||
|
||||
// Verify deterministic generation: same SessionId should produce identical access key ID
|
||||
// (based on hash of session ID, not random)
|
||||
assert.Equal(t, sessionInfo1.Credentials.AccessKeyId, sessionInfo2.Credentials.AccessKeyId,
|
||||
"same session ID should produce identical access key ID (deterministic hash-based generation)")
|
||||
|
||||
// Session token is also deterministic (hash-based on session ID)
|
||||
assert.Equal(t, sessionInfo1.Credentials.SessionToken, sessionInfo2.Credentials.SessionToken,
|
||||
"same session ID should produce identical session token (deterministic hash-based generation)")
|
||||
|
||||
// Secret access key is NOW deterministic (hash-based on session ID, not random!)
|
||||
// This is critical for signature verification: the same session ID must regenerate
|
||||
// the same secret key so that signature verification succeeds.
|
||||
assert.Equal(t, sessionInfo1.Credentials.SecretAccessKey, sessionInfo2.Credentials.SecretAccessKey,
|
||||
"same session ID should produce identical secret access key (deterministic hash-based generation)")
|
||||
|
||||
// Expiration should match
|
||||
assert.WithinDuration(t, sessionInfo1.Credentials.Expiration, sessionInfo2.Credentials.Expiration, 1*time.Second,
|
||||
"credentials expiration should match")
|
||||
}
|
||||
|
||||
// TestSTSSessionClaimsToSessionInfoPreservesAllFields tests that all fields are preserved
|
||||
func TestSTSSessionClaimsToSessionInfoPreservesAllFields(t *testing.T) {
|
||||
sessionId := "test-session-id"
|
||||
issuer := "test-issuer"
|
||||
expiresAt := time.Now().Add(2 * time.Hour)
|
||||
|
||||
policies := []string{"policy1", "policy2"}
|
||||
requestContext := map[string]interface{}{
|
||||
"sourceIp": "192.168.1.1",
|
||||
"userAgent": "test-agent",
|
||||
}
|
||||
|
||||
claims := NewSTSSessionClaims(sessionId, issuer, expiresAt).
|
||||
WithSessionName("session-name").
|
||||
WithRoleInfo("role-arn", "assumed-role", "principal").
|
||||
WithIdentityProvider("provider", "external-id", "issuer").
|
||||
WithPolicies(policies).
|
||||
WithRequestContext(requestContext).
|
||||
WithMaxDuration(2 * time.Hour)
|
||||
|
||||
sessionInfo := claims.ToSessionInfo()
|
||||
|
||||
// Verify all fields are preserved
|
||||
assert.Equal(t, sessionId, sessionInfo.SessionId)
|
||||
assert.Equal(t, "session-name", sessionInfo.SessionName)
|
||||
assert.Equal(t, "role-arn", sessionInfo.RoleArn)
|
||||
assert.Equal(t, "assumed-role", sessionInfo.AssumedRoleUser)
|
||||
assert.Equal(t, "principal", sessionInfo.Principal)
|
||||
assert.Equal(t, "provider", sessionInfo.IdentityProvider)
|
||||
assert.Equal(t, "external-id", sessionInfo.ExternalUserId)
|
||||
assert.Equal(t, "issuer", sessionInfo.ProviderIssuer)
|
||||
assert.Equal(t, policies, sessionInfo.Policies)
|
||||
assert.Equal(t, requestContext, sessionInfo.RequestContext)
|
||||
assert.WithinDuration(t, expiresAt, sessionInfo.ExpiresAt, 1*time.Second)
|
||||
}
|
||||
|
||||
// TestSTSSessionClaimsToSessionInfoEmptyFields tests handling of empty/nil fields
|
||||
func TestSTSSessionClaimsToSessionInfoEmptyFields(t *testing.T) {
|
||||
sessionId := "minimal-session"
|
||||
issuer := "issuer"
|
||||
expiresAt := time.Now().Add(time.Hour)
|
||||
|
||||
// Create claims with minimal fields
|
||||
claims := NewSTSSessionClaims(sessionId, issuer, expiresAt)
|
||||
|
||||
sessionInfo := claims.ToSessionInfo()
|
||||
|
||||
// Verify basic fields are preserved
|
||||
assert.Equal(t, sessionId, sessionInfo.SessionId)
|
||||
assert.Empty(t, sessionInfo.SessionName)
|
||||
assert.Empty(t, sessionInfo.RoleArn)
|
||||
|
||||
// Verify credentials are still generated even with minimal fields
|
||||
assert.NotNil(t, sessionInfo.Credentials)
|
||||
assert.NotEmpty(t, sessionInfo.Credentials.AccessKeyId)
|
||||
assert.NotEmpty(t, sessionInfo.Credentials.SecretAccessKey)
|
||||
}
|
||||
|
||||
// TestSTSSessionClaimsToSessionInfoCredentialExpiration tests credential expiration
|
||||
func TestSTSSessionClaimsToSessionInfoCredentialExpiration(t *testing.T) {
|
||||
sessionId := "test-session"
|
||||
issuer := "issuer"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
expiresAt time.Time
|
||||
expectNotExpired bool
|
||||
description string
|
||||
}{
|
||||
{
|
||||
name: "future_expiration",
|
||||
expiresAt: time.Now().Add(time.Hour),
|
||||
expectNotExpired: true,
|
||||
description: "Credentials should not be expired if ExpiresAt is in the future",
|
||||
},
|
||||
{
|
||||
name: "past_expiration",
|
||||
expiresAt: time.Now().Add(-time.Hour),
|
||||
expectNotExpired: false,
|
||||
description: "Credentials should be expired if ExpiresAt is in the past",
|
||||
},
|
||||
{
|
||||
name: "near_future_expiration",
|
||||
expiresAt: time.Now().Add(time.Minute),
|
||||
expectNotExpired: true,
|
||||
description: "Credentials should not be expired even if close to expiration",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
claims := NewSTSSessionClaims(sessionId, issuer, tc.expiresAt)
|
||||
sessionInfo := claims.ToSessionInfo()
|
||||
|
||||
assert.NotNil(t, sessionInfo.Credentials)
|
||||
// Check expiration within 1 second due to timing precision (symmetric tolerance)
|
||||
assert.WithinDuration(t, tc.expiresAt, sessionInfo.Credentials.Expiration, time.Second,
|
||||
"credential expiration should be within 1 second of session expiration")
|
||||
// We set tc.expiresAt to past/future values to exercise expiration handling.
|
||||
// Assert the credentials' expiration relative to now to exercise code behavior
|
||||
if tc.expectNotExpired {
|
||||
assert.True(t, time.Now().Before(sessionInfo.Credentials.Expiration), tc.description)
|
||||
} else {
|
||||
assert.True(t, time.Now().After(sessionInfo.Credentials.Expiration), tc.description)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSessionInfoIntegration tests the full integration of session info flow
|
||||
func TestSessionInfoIntegration(t *testing.T) {
|
||||
// Create a session claim
|
||||
sessionId, err := GenerateSessionId()
|
||||
require.NoError(t, err)
|
||||
|
||||
expiresAt := time.Now().Add(time.Hour)
|
||||
claims := NewSTSSessionClaims(sessionId, "test-issuer", expiresAt).
|
||||
WithSessionName("integration-test").
|
||||
WithRoleInfo(
|
||||
"arn:aws:iam::123456789012:role/integration",
|
||||
"arn:aws:iam::123456789012:assumed-role/integration/test",
|
||||
"arn:aws:iam::123456789012:assumed-role/integration/test",
|
||||
).
|
||||
WithIdentityProvider("test-provider", "user-id", "https://test.example.com")
|
||||
|
||||
// Convert to SessionInfo
|
||||
sessionInfo := claims.ToSessionInfo()
|
||||
|
||||
// Verify the session info has valid credentials
|
||||
assert.NotNil(t, sessionInfo.Credentials)
|
||||
assert.NotEmpty(t, sessionInfo.Credentials.AccessKeyId)
|
||||
assert.NotEmpty(t, sessionInfo.Credentials.SecretAccessKey)
|
||||
|
||||
// Verify basic session properties
|
||||
assert.Equal(t, sessionId, sessionInfo.SessionId)
|
||||
assert.Equal(t, "integration-test", sessionInfo.SessionName)
|
||||
assert.False(t, sessionInfo.ExpiresAt.IsZero())
|
||||
|
||||
// Verify that the session is valid
|
||||
assert.True(t, sessionInfo.ExpiresAt.After(time.Now()), "session should not be expired")
|
||||
assert.False(t, sessionInfo.Credentials.Expiration.Before(time.Now()), "credentials should not be expired")
|
||||
}
|
||||
|
||||
// TestSecretAccessKeyDeterminism verifies that secret access keys are deterministically
|
||||
// generated from the session ID. This is CRITICAL for STS signature verification:
|
||||
// The client generates a secret key and signs the request. When the server receives
|
||||
// the request, it must regenerate the exact same secret key from the JWT claims
|
||||
// to verify the signature. If the secret key is random, verification will always fail.
|
||||
func TestSecretAccessKeyDeterminism(t *testing.T) {
|
||||
sessionId := "critical-determinism-test"
|
||||
expiration := time.Now().Add(time.Hour)
|
||||
|
||||
// Generate credentials multiple times with the same session ID
|
||||
credGen := NewCredentialGenerator()
|
||||
|
||||
cred1, err := credGen.GenerateTemporaryCredentials(sessionId, expiration)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, cred1)
|
||||
|
||||
cred2, err := credGen.GenerateTemporaryCredentials(sessionId, expiration)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, cred2)
|
||||
|
||||
cred3, err := credGen.GenerateTemporaryCredentials(sessionId, expiration)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, cred3)
|
||||
|
||||
// All three should have IDENTICAL secret access keys
|
||||
assert.Equal(t, cred1.SecretAccessKey, cred2.SecretAccessKey,
|
||||
"same sessionId must produce identical secret key on first and second call")
|
||||
assert.Equal(t, cred2.SecretAccessKey, cred3.SecretAccessKey,
|
||||
"same sessionId must produce identical secret key on second and third call")
|
||||
|
||||
// All three should have IDENTICAL access key IDs
|
||||
assert.Equal(t, cred1.AccessKeyId, cred2.AccessKeyId,
|
||||
"same sessionId must produce identical access key ID")
|
||||
assert.Equal(t, cred2.AccessKeyId, cred3.AccessKeyId,
|
||||
"same sessionId must produce identical access key ID")
|
||||
|
||||
// All three should have IDENTICAL session tokens
|
||||
assert.Equal(t, cred1.SessionToken, cred2.SessionToken,
|
||||
"same sessionId must produce identical session token")
|
||||
assert.Equal(t, cred2.SessionToken, cred3.SessionToken,
|
||||
"same sessionId must produce identical session token")
|
||||
|
||||
// Different session IDs should produce different secrets
|
||||
otherSessionId := "different-session"
|
||||
credOther, err := credGen.GenerateTemporaryCredentials(otherSessionId, expiration)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, credOther)
|
||||
|
||||
assert.NotEqual(t, cred1.SecretAccessKey, credOther.SecretAccessKey,
|
||||
"different session IDs must produce different secret keys")
|
||||
assert.NotEqual(t, cred1.AccessKeyId, credOther.AccessKeyId,
|
||||
"different session IDs must produce different access key IDs")
|
||||
assert.NotEqual(t, cred1.SessionToken, credOther.SessionToken,
|
||||
"different session IDs must produce different session tokens")
|
||||
}
|
||||
@@ -699,8 +699,13 @@ func (s *STSService) validateRoleAssumptionForWebIdentity(ctx context.Context, r
|
||||
return fmt.Errorf("web identity token cannot be empty")
|
||||
}
|
||||
|
||||
// Validate role ARN and extract role name
|
||||
// Accepts both arn:aws:iam::role/X and arn:aws:iam::ACCOUNT:role/X
|
||||
// Basic role ARN format validation
|
||||
expectedPrefix := "arn:aws:iam::role/"
|
||||
if len(roleArn) < len(expectedPrefix) || roleArn[:len(expectedPrefix)] != expectedPrefix {
|
||||
return fmt.Errorf("invalid role ARN format: got %s, expected format: %s*", roleArn, expectedPrefix)
|
||||
}
|
||||
|
||||
// Extract role name and validate ARN format
|
||||
roleName := utils.ExtractRoleNameFromArn(roleArn)
|
||||
if roleName == "" {
|
||||
return fmt.Errorf("invalid role ARN format: %s", roleArn)
|
||||
@@ -731,8 +736,13 @@ func (s *STSService) validateRoleAssumptionForCredentials(ctx context.Context, r
|
||||
return fmt.Errorf("identity cannot be nil")
|
||||
}
|
||||
|
||||
// Validate role ARN and extract role name
|
||||
// Accepts both arn:aws:iam::role/X and arn:aws:iam::ACCOUNT:role/X
|
||||
// Basic role ARN format validation
|
||||
expectedPrefix := "arn:aws:iam::role/"
|
||||
if len(roleArn) < len(expectedPrefix) || roleArn[:len(expectedPrefix)] != expectedPrefix {
|
||||
return fmt.Errorf("invalid role ARN format: got %s, expected format: %s*", roleArn, expectedPrefix)
|
||||
}
|
||||
|
||||
// Extract role name and validate ARN format
|
||||
roleName := utils.ExtractRoleNameFromArn(roleArn)
|
||||
if roleName == "" {
|
||||
return fmt.Errorf("invalid role ARN format: %s", roleArn)
|
||||
|
||||
+11
-11
@@ -149,7 +149,7 @@ func (c *CredentialGenerator) GenerateTemporaryCredentials(sessionId string, exp
|
||||
return nil, fmt.Errorf("failed to generate access key ID: %w", err)
|
||||
}
|
||||
|
||||
secretAccessKey, err := c.generateSecretAccessKey(sessionId)
|
||||
secretAccessKey, err := c.generateSecretAccessKey()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate secret access key: %w", err)
|
||||
}
|
||||
@@ -174,16 +174,16 @@ func (c *CredentialGenerator) generateAccessKeyId(sessionId string) (string, err
|
||||
return "AKIA" + hex.EncodeToString(hash[:8]), nil // AWS format: AKIA + 16 chars
|
||||
}
|
||||
|
||||
// generateSecretAccessKey generates a deterministic secret access key based on sessionId
|
||||
// This ensures the same secret key is regenerated from the JWT claims during signature verification
|
||||
func (c *CredentialGenerator) generateSecretAccessKey(sessionId string) (string, error) {
|
||||
// Create deterministic secret key based on session ID (not random!)
|
||||
// This is critical for STS because:
|
||||
// 1. AssumeRoleWithWebIdentity generates the secret key once
|
||||
// 2. During signature verification, ToSessionInfo() regenerates credentials from JWT
|
||||
// 3. Both must generate the same secret key for signature verification to succeed
|
||||
hash := sha256.Sum256([]byte("secret-key:" + sessionId))
|
||||
return base64.StdEncoding.EncodeToString(hash[:]), nil
|
||||
// generateSecretAccessKey generates a random secret access key
|
||||
func (c *CredentialGenerator) generateSecretAccessKey() (string, error) {
|
||||
// Generate 32 random bytes for secret key
|
||||
secretBytes := make([]byte, 32)
|
||||
_, err := rand.Read(secretBytes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return base64.StdEncoding.EncodeToString(secretBytes), nil
|
||||
}
|
||||
|
||||
// generateSessionTokenId generates a session token identifier
|
||||
|
||||
+23
-25
@@ -3,39 +3,37 @@ package utils
|
||||
import "strings"
|
||||
|
||||
// ExtractRoleNameFromPrincipal extracts role name from principal ARN
|
||||
// Handles both STS assumed role and IAM role formats with or without account ID:
|
||||
// - arn:aws:sts::assumed-role/Role/Session (legacy)
|
||||
// - arn:aws:sts::ACCOUNT:assumed-role/Role/Session (standard)
|
||||
// - arn:aws:iam::role/Role (legacy)
|
||||
// - arn:aws:iam::ACCOUNT:role/Role (standard)
|
||||
// Handles both STS assumed role and IAM role formats
|
||||
func ExtractRoleNameFromPrincipal(principal string) string {
|
||||
// Handle STS assumed role format
|
||||
if strings.HasPrefix(principal, "arn:aws:sts::") {
|
||||
remainder := principal[len("arn:aws:sts::"):]
|
||||
if idx := strings.Index(remainder, "assumed-role/"); idx != -1 {
|
||||
afterMarker := remainder[idx+len("assumed-role/"):]
|
||||
if slash := strings.Index(afterMarker, "/"); slash != -1 {
|
||||
return afterMarker[:slash]
|
||||
}
|
||||
return afterMarker
|
||||
// Handle STS assumed role format: arn:aws:sts::assumed-role/RoleName/SessionName
|
||||
stsPrefix := "arn:aws:sts::assumed-role/"
|
||||
if strings.HasPrefix(principal, stsPrefix) {
|
||||
remainder := principal[len(stsPrefix):]
|
||||
// Split on first '/' to get role name
|
||||
if slashIndex := strings.Index(remainder, "/"); slashIndex != -1 {
|
||||
return remainder[:slashIndex]
|
||||
}
|
||||
// If no slash found, return the remainder (edge case)
|
||||
return remainder
|
||||
}
|
||||
|
||||
// Handle IAM role format
|
||||
return ExtractRoleNameFromArn(principal)
|
||||
// Handle IAM role format: arn:aws:iam::role/RoleName
|
||||
iamPrefix := "arn:aws:iam::role/"
|
||||
if strings.HasPrefix(principal, iamPrefix) {
|
||||
return principal[len(iamPrefix):]
|
||||
}
|
||||
|
||||
// Return empty string to signal invalid ARN format
|
||||
// This allows callers to handle the error explicitly instead of masking it
|
||||
return ""
|
||||
}
|
||||
|
||||
// ExtractRoleNameFromArn extracts role name from an IAM role ARN
|
||||
// Handles both formats:
|
||||
// - arn:aws:iam::role/RoleName (legacy, without account ID)
|
||||
// - arn:aws:iam::ACCOUNT:role/RoleName (standard AWS format)
|
||||
// Specifically handles: arn:aws:iam::role/RoleName
|
||||
func ExtractRoleNameFromArn(roleArn string) string {
|
||||
if !strings.HasPrefix(roleArn, "arn:aws:iam::") {
|
||||
return ""
|
||||
}
|
||||
remainder := roleArn[len("arn:aws:iam::"):]
|
||||
if idx := strings.Index(remainder, "role/"); idx != -1 {
|
||||
return remainder[idx+len("role/"):]
|
||||
prefix := "arn:aws:iam::role/"
|
||||
if strings.HasPrefix(roleArn, prefix) && len(roleArn) > len(prefix) {
|
||||
return roleArn[len(prefix):]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package utils
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestExtractRoleNameFromArn(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
roleArn string
|
||||
expected string
|
||||
}{
|
||||
// Legacy format (without account ID)
|
||||
{
|
||||
name: "legacy_format_simple_role_name",
|
||||
roleArn: "arn:aws:iam::role/default",
|
||||
expected: "default",
|
||||
},
|
||||
{
|
||||
name: "legacy_format_custom_role_name",
|
||||
roleArn: "arn:aws:iam::role/MyRole",
|
||||
expected: "MyRole",
|
||||
},
|
||||
{
|
||||
name: "legacy_format_with_path",
|
||||
roleArn: "arn:aws:iam::role/Path/MyRole",
|
||||
expected: "Path/MyRole",
|
||||
},
|
||||
{
|
||||
name: "legacy_format_with_nested_path",
|
||||
roleArn: "arn:aws:iam::role/Division/Team/Role",
|
||||
expected: "Division/Team/Role",
|
||||
},
|
||||
// Standard AWS format (with account ID)
|
||||
{
|
||||
name: "standard_format_simple_role_name",
|
||||
roleArn: "arn:aws:iam::123456789012:role/default",
|
||||
expected: "default",
|
||||
},
|
||||
{
|
||||
name: "standard_format_custom_role_name",
|
||||
roleArn: "arn:aws:iam::999999999999:role/MyRole",
|
||||
expected: "MyRole",
|
||||
},
|
||||
{
|
||||
name: "standard_format_with_path",
|
||||
roleArn: "arn:aws:iam::123456789012:role/Path/MyRole",
|
||||
expected: "Path/MyRole",
|
||||
},
|
||||
{
|
||||
name: "standard_format_with_nested_path",
|
||||
roleArn: "arn:aws:iam::123456789012:role/Division/Team/Role",
|
||||
expected: "Division/Team/Role",
|
||||
},
|
||||
// Edge cases and invalid formats
|
||||
{
|
||||
name: "invalid_arn_missing_prefix",
|
||||
roleArn: "invalid-arn",
|
||||
expected: "",
|
||||
},
|
||||
{
|
||||
name: "invalid_arn_incomplete",
|
||||
roleArn: "arn:aws:iam::",
|
||||
expected: "",
|
||||
},
|
||||
{
|
||||
name: "invalid_arn_no_role_marker",
|
||||
roleArn: "arn:aws:iam::123456789012:user/username",
|
||||
expected: "",
|
||||
},
|
||||
{
|
||||
name: "invalid_arn_wrong_service",
|
||||
roleArn: "arn:aws:sts::assumed-role/Role/Session",
|
||||
expected: "",
|
||||
},
|
||||
{
|
||||
name: "empty_string",
|
||||
roleArn: "",
|
||||
expected: "",
|
||||
},
|
||||
{
|
||||
name: "role_marker_no_name",
|
||||
roleArn: "arn:aws:iam::role/",
|
||||
expected: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
result := ExtractRoleNameFromArn(tc.roleArn)
|
||||
if result != tc.expected {
|
||||
t.Errorf("ExtractRoleNameFromArn(%q) = %q, want %q", tc.roleArn, result, tc.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractRoleNameFromPrincipal(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
principal string
|
||||
expected string
|
||||
}{
|
||||
// STS assumed role format (legacy)
|
||||
{
|
||||
name: "sts_assumed_role_legacy",
|
||||
principal: "arn:aws:sts::assumed-role/RoleName/SessionName",
|
||||
expected: "RoleName",
|
||||
},
|
||||
{
|
||||
name: "sts_assumed_role_legacy_no_session",
|
||||
principal: "arn:aws:sts::assumed-role/RoleName",
|
||||
expected: "RoleName",
|
||||
},
|
||||
// STS assumed role format (standard with account ID)
|
||||
{
|
||||
name: "sts_assumed_role_standard",
|
||||
principal: "arn:aws:sts::123456789012:assumed-role/RoleName/SessionName",
|
||||
expected: "RoleName",
|
||||
},
|
||||
{
|
||||
name: "sts_assumed_role_standard_no_session",
|
||||
principal: "arn:aws:sts::123456789012:assumed-role/RoleName",
|
||||
expected: "RoleName",
|
||||
},
|
||||
// IAM role format (legacy)
|
||||
{
|
||||
name: "iam_role_legacy",
|
||||
principal: "arn:aws:iam::role/RoleName",
|
||||
expected: "RoleName",
|
||||
},
|
||||
{
|
||||
name: "iam_role_legacy_with_path",
|
||||
principal: "arn:aws:iam::role/Path/RoleName",
|
||||
expected: "Path/RoleName",
|
||||
},
|
||||
// IAM role format (standard)
|
||||
{
|
||||
name: "iam_role_standard",
|
||||
principal: "arn:aws:iam::123456789012:role/RoleName",
|
||||
expected: "RoleName",
|
||||
},
|
||||
{
|
||||
name: "iam_role_standard_with_path",
|
||||
principal: "arn:aws:iam::123456789012:role/Path/RoleName",
|
||||
expected: "Path/RoleName",
|
||||
},
|
||||
// Invalid formats
|
||||
{
|
||||
name: "invalid_principal",
|
||||
principal: "invalid-arn",
|
||||
expected: "",
|
||||
},
|
||||
{
|
||||
name: "empty_string",
|
||||
principal: "",
|
||||
expected: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
result := ExtractRoleNameFromPrincipal(tc.principal)
|
||||
if result != tc.expected {
|
||||
t.Errorf("ExtractRoleNameFromPrincipal(%q) = %q, want %q", tc.principal, result, tc.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/hanwen/go-fuse/v2/fuse"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func grpcErrorToFuseStatus(err error) fuse.Status {
|
||||
if err == nil {
|
||||
return fuse.OK
|
||||
}
|
||||
|
||||
// Unpack error for inspection
|
||||
if s, ok := status.FromError(err); ok {
|
||||
switch s.Code() {
|
||||
case codes.OK:
|
||||
return fuse.OK
|
||||
case codes.Canceled, codes.DeadlineExceeded:
|
||||
return fuse.Status(syscall.ETIMEDOUT)
|
||||
case codes.Unavailable:
|
||||
return fuse.Status(syscall.EAGAIN)
|
||||
case codes.ResourceExhausted:
|
||||
return fuse.Status(syscall.EAGAIN) // Or syscall.ENOSPC
|
||||
case codes.PermissionDenied:
|
||||
return fuse.Status(syscall.EACCES)
|
||||
case codes.Unauthenticated:
|
||||
return fuse.Status(syscall.EPERM)
|
||||
case codes.NotFound:
|
||||
return fuse.ENOENT
|
||||
case codes.AlreadyExists:
|
||||
return fuse.Status(syscall.EEXIST)
|
||||
case codes.InvalidArgument:
|
||||
return fuse.EINVAL
|
||||
}
|
||||
}
|
||||
|
||||
// String matching for errors that don't have proper gRPC codes but are known
|
||||
errStr := err.Error()
|
||||
if strings.Contains(errStr, "transport") {
|
||||
return fuse.Status(syscall.EAGAIN)
|
||||
}
|
||||
// Add other string matches if necessary
|
||||
|
||||
return fuse.EIO
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
@@ -27,7 +28,7 @@ func (wfs *WFS) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFile
|
||||
}, filerGrpcAddress, false, wfs.option.GrpcDialOption)
|
||||
|
||||
if err != nil {
|
||||
// glog.V(0).Infof("WithFilerClient %d %v: %v", x, filerGrpcAddress, err)
|
||||
glog.V(0).Infof("WithFilerClient %d %v: %v", x, filerGrpcAddress, err)
|
||||
} else {
|
||||
atomic.StoreInt32(&wfs.option.filerIndex, i)
|
||||
return nil
|
||||
|
||||
+4
-11
@@ -3,13 +3,12 @@ package mount
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"syscall"
|
||||
|
||||
"github.com/hanwen/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func (wfs *WFS) saveEntry(path util.FullPath, entry *filer_pb.Entry) (code fuse.Status) {
|
||||
@@ -34,20 +33,14 @@ func (wfs *WFS) saveEntry(path util.FullPath, entry *filer_pb.Entry) (code fuse.
|
||||
}
|
||||
|
||||
if err := wfs.metaCache.UpdateEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
|
||||
return fmt.Errorf("metaCache.UpdateEntry dir %s: %w", path, err)
|
||||
return fmt.Errorf("UpdateEntry dir %s: %v", path, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
// glog.V(0).Infof("saveEntry %s: %v", path, err)
|
||||
fuseStatus := grpcErrorToFuseStatus(err)
|
||||
if fuseStatus == fuse.EIO {
|
||||
glog.Errorf("saveEntry failed for %s: %v (returning EIO)", path, err)
|
||||
} else {
|
||||
glog.V(1).Infof("saveEntry failed for %s: %v (returning %v)", path, err, fuseStatus)
|
||||
}
|
||||
return fuseStatus
|
||||
glog.Errorf("saveEntry %s: %v", path, err)
|
||||
return fuse.EIO
|
||||
}
|
||||
|
||||
return fuse.OK
|
||||
|
||||
@@ -257,15 +257,6 @@ func hostAndPort(address string) (host string, port uint64, err error) {
|
||||
if colonIndex < 0 {
|
||||
return "", 0, fmt.Errorf("server should have hostname:port format: %v", address)
|
||||
}
|
||||
dotIndex := strings.LastIndex(address, ".")
|
||||
if dotIndex > colonIndex {
|
||||
// port format is "port.grpcPort"
|
||||
port, err = strconv.ParseUint(address[colonIndex+1:dotIndex], 10, 64)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("server port parse error: %w", err)
|
||||
}
|
||||
return address[:colonIndex], port, err
|
||||
}
|
||||
port, err = strconv.ParseUint(address[colonIndex+1:], 10, 64)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("server port parse error: %w", err)
|
||||
@@ -276,19 +267,6 @@ func hostAndPort(address string) (host string, port uint64, err error) {
|
||||
|
||||
func ServerToGrpcAddress(server string) (serverGrpcAddress string) {
|
||||
|
||||
colonIndex := strings.LastIndex(server, ":")
|
||||
if colonIndex >= 0 {
|
||||
if dotIndex := strings.LastIndex(server, "."); dotIndex > colonIndex {
|
||||
// port format is "port.grpcPort"
|
||||
// return the host:grpcPort
|
||||
host := server[:colonIndex]
|
||||
grpcPort := server[dotIndex+1:]
|
||||
if _, err := strconv.ParseUint(grpcPort, 10, 64); err == nil {
|
||||
return util.JoinHostPort(host, int(0+util.ParseInt(grpcPort, 0)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
host, port, parseErr := hostAndPort(server)
|
||||
if parseErr != nil {
|
||||
glog.Fatalf("server address %s parse error: %v", server, parseErr)
|
||||
|
||||
@@ -951,75 +951,32 @@ func (iam *IdentityAccessManagement) authenticateJWTWithIAM(r *http.Request) (*I
|
||||
return identity, s3err.ErrNone
|
||||
}
|
||||
|
||||
// IAM authorization path type constants
|
||||
// iamAuthPath represents the type of IAM authorization path
|
||||
type iamAuthPath string
|
||||
|
||||
// IAM authorization path constants
|
||||
const (
|
||||
iamAuthPathJWT iamAuthPath = "jwt"
|
||||
iamAuthPathSTS_V4 iamAuthPath = "sts_v4"
|
||||
iamAuthPathStatic_V4 iamAuthPath = "static_v4"
|
||||
iamAuthPathNone iamAuthPath = "none"
|
||||
)
|
||||
|
||||
// determineIAMAuthPath determines the IAM authorization path based on available tokens and principals
|
||||
func determineIAMAuthPath(sessionToken, principal, principalArn string) iamAuthPath {
|
||||
if sessionToken != "" && principal != "" {
|
||||
return iamAuthPathJWT
|
||||
} else if sessionToken != "" && principalArn != "" {
|
||||
return iamAuthPathSTS_V4
|
||||
} else if principalArn != "" {
|
||||
return iamAuthPathStatic_V4
|
||||
}
|
||||
return iamAuthPathNone
|
||||
}
|
||||
|
||||
// authorizeWithIAM authorizes requests using the IAM integration policy engine
|
||||
func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity *Identity, action Action, bucket string, object string) s3err.ErrorCode {
|
||||
ctx := r.Context()
|
||||
|
||||
// Get session info from request headers
|
||||
// First check for JWT-based authentication headers (X-SeaweedFS-Session-Token)
|
||||
// Get session info from request headers (for JWT-based authentication)
|
||||
sessionToken := r.Header.Get("X-SeaweedFS-Session-Token")
|
||||
principal := r.Header.Get("X-SeaweedFS-Principal")
|
||||
|
||||
// Fallback to AWS Signature V4 STS token if JWT token not present
|
||||
// This handles the case where STS AssumeRoleWithWebIdentity generates temporary credentials
|
||||
// that include an X-Amz-Security-Token header (in addition to the access key and secret)
|
||||
if sessionToken == "" {
|
||||
sessionToken = r.Header.Get("X-Amz-Security-Token")
|
||||
if sessionToken == "" {
|
||||
// Also check query parameters for presigned URLs with STS tokens
|
||||
sessionToken = r.URL.Query().Get("X-Amz-Security-Token")
|
||||
}
|
||||
}
|
||||
|
||||
// Create IAMIdentity for authorization
|
||||
iamIdentity := &IAMIdentity{
|
||||
Name: identity.Name,
|
||||
Account: identity.Account,
|
||||
}
|
||||
|
||||
// Determine authorization path and configure identity
|
||||
authPath := determineIAMAuthPath(sessionToken, principal, identity.PrincipalArn)
|
||||
switch authPath {
|
||||
case iamAuthPathJWT:
|
||||
// Handle both session-based (JWT) and static-key-based (V4 signature) principals
|
||||
if sessionToken != "" && principal != "" {
|
||||
// JWT-based authentication - use session token and principal from headers
|
||||
iamIdentity.Principal = principal
|
||||
iamIdentity.SessionToken = sessionToken
|
||||
glog.V(3).Infof("Using JWT-based IAM authorization for principal: %s", principal)
|
||||
case iamAuthPathSTS_V4:
|
||||
// STS V4 signature authentication - use session token (from X-Amz-Security-Token) with principal ARN
|
||||
} else if identity.PrincipalArn != "" {
|
||||
// V4 signature authentication - use principal ARN from identity
|
||||
iamIdentity.Principal = identity.PrincipalArn
|
||||
iamIdentity.SessionToken = sessionToken
|
||||
glog.V(3).Infof("Using STS V4 signature IAM authorization for principal: %s with session token", identity.PrincipalArn)
|
||||
case iamAuthPathStatic_V4:
|
||||
// Static V4 signature authentication - use principal ARN without session token
|
||||
iamIdentity.Principal = identity.PrincipalArn
|
||||
iamIdentity.SessionToken = ""
|
||||
glog.V(3).Infof("Using static V4 signature IAM authorization for principal: %s", identity.PrincipalArn)
|
||||
default:
|
||||
iamIdentity.SessionToken = "" // No session token for static credentials
|
||||
glog.V(3).Infof("Using V4 signature IAM authorization for principal: %s", identity.PrincipalArn)
|
||||
} else {
|
||||
glog.V(3).Info("No valid principal information for IAM authorization")
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
+23
-118
@@ -205,40 +205,32 @@ func (iam *IdentityAccessManagement) verifyV4Signature(r *http.Request, shouldCh
|
||||
return nil, nil, "", nil, errCode
|
||||
}
|
||||
|
||||
var cred *Credential
|
||||
// 2. Lookup user and credentials
|
||||
identity, cred, found := iam.lookupByAccessKey(authInfo.AccessKey)
|
||||
if !found {
|
||||
// Log detailed error information for InvalidAccessKeyId
|
||||
iam.m.RLock()
|
||||
availableKeys := make([]string, 0, len(iam.accessKeyIdent))
|
||||
for key := range iam.accessKeyIdent {
|
||||
availableKeys = append(availableKeys, key)
|
||||
}
|
||||
iam.m.RUnlock()
|
||||
|
||||
// 2. Check for STS session token
|
||||
sessionToken := r.Header.Get("X-Amz-Security-Token")
|
||||
if sessionToken == "" {
|
||||
sessionToken = r.URL.Query().Get("X-Amz-Security-Token")
|
||||
glog.Warningf("InvalidAccessKeyId: attempted key '%s' not found. Available keys: %d, Auth enabled: %v",
|
||||
authInfo.AccessKey, len(availableKeys), iam.isAuthEnabled)
|
||||
|
||||
if glog.V(2) && len(availableKeys) > 0 {
|
||||
glog.V(2).Infof("Available access keys: %v", availableKeys)
|
||||
}
|
||||
|
||||
return nil, nil, "", nil, s3err.ErrInvalidAccessKeyID
|
||||
}
|
||||
if sessionToken != "" {
|
||||
// Validate STS session token
|
||||
identity, cred, errCode = iam.validateSTSSessionToken(r, sessionToken, authInfo.AccessKey)
|
||||
if errCode != s3err.ErrNone {
|
||||
return nil, nil, "", nil, errCode
|
||||
}
|
||||
} else {
|
||||
// 3. Lookup user and credentials
|
||||
var found bool
|
||||
identity, cred, found = iam.lookupByAccessKey(authInfo.AccessKey)
|
||||
if !found {
|
||||
// Log detailed error information for InvalidAccessKeyId (avoid slice allocation for performance)
|
||||
iam.m.RLock()
|
||||
keyCount := len(iam.accessKeyIdent)
|
||||
iam.m.RUnlock()
|
||||
|
||||
glog.Warningf("InvalidAccessKeyId: attempted key '%s' not found. Available keys: %d, Auth enabled: %v",
|
||||
authInfo.AccessKey, keyCount, iam.isAuthEnabled)
|
||||
return nil, nil, "", nil, s3err.ErrInvalidAccessKeyID
|
||||
}
|
||||
|
||||
// Check service account expiration
|
||||
if cred.isCredentialExpired() {
|
||||
glog.V(2).Infof("Service account credential %s has expired (expiration: %d, now: %d)",
|
||||
authInfo.AccessKey, cred.Expiration, time.Now().Unix())
|
||||
return nil, nil, "", nil, s3err.ErrAccessDenied
|
||||
}
|
||||
// Check service account expiration
|
||||
if cred.isCredentialExpired() {
|
||||
glog.V(2).Infof("Service account credential %s has expired (expiration: %d, now: %d)",
|
||||
authInfo.AccessKey, cred.Expiration, time.Now().Unix())
|
||||
return nil, nil, "", nil, s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
// 3. Perform permission check
|
||||
@@ -299,93 +291,6 @@ func (iam *IdentityAccessManagement) verifyV4Signature(r *http.Request, shouldCh
|
||||
return identity, cred, calculatedSignature, authInfo, s3err.ErrNone
|
||||
}
|
||||
|
||||
// validateSTSSessionToken validates an STS session token and extracts temporary credentials
|
||||
func (iam *IdentityAccessManagement) validateSTSSessionToken(r *http.Request, sessionToken string, accessKey string) (*Identity, *Credential, s3err.ErrorCode) {
|
||||
// Check if IAM integration with STS is available
|
||||
if iam.iamIntegration == nil || iam.iamIntegration.stsService == nil {
|
||||
glog.V(2).Infof("STS service not available, cannot validate session token")
|
||||
return nil, nil, s3err.ErrInvalidAccessKeyID
|
||||
}
|
||||
|
||||
// Validate the session token with the STS service
|
||||
ctx := r.Context()
|
||||
sessionInfo, err := iam.iamIntegration.stsService.ValidateSessionToken(ctx, sessionToken)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("Failed to validate STS session token: %v", err)
|
||||
return nil, nil, s3err.ErrInvalidAccessKeyID
|
||||
}
|
||||
|
||||
// Check if sessionInfo is nil
|
||||
if sessionInfo == nil {
|
||||
glog.Warningf("STS service returned nil session info for token validation")
|
||||
return nil, nil, s3err.ErrInvalidAccessKeyID
|
||||
}
|
||||
|
||||
// Check if Credentials are nil
|
||||
if sessionInfo.Credentials == nil {
|
||||
glog.Warningf("STS service returned nil credentials in session info")
|
||||
return nil, nil, s3err.ErrInvalidAccessKeyID
|
||||
}
|
||||
|
||||
// Validate that credentials have the required access key
|
||||
if sessionInfo.Credentials.AccessKeyId == "" {
|
||||
glog.Warningf("STS service returned empty AccessKeyId in credentials")
|
||||
return nil, nil, s3err.ErrInvalidAccessKeyID
|
||||
}
|
||||
|
||||
// Verify that the access key in the request matches the one in the session token
|
||||
if sessionInfo.Credentials.AccessKeyId != accessKey {
|
||||
glog.V(2).Infof("Access key mismatch: request has %s, session token has %s",
|
||||
accessKey, sessionInfo.Credentials.AccessKeyId)
|
||||
return nil, nil, s3err.ErrInvalidAccessKeyID
|
||||
}
|
||||
|
||||
// Check if the session has expired
|
||||
if sessionInfo.ExpiresAt.IsZero() {
|
||||
glog.Warningf("STS service returned zero/empty expiration time")
|
||||
return nil, nil, s3err.ErrInvalidAccessKeyID
|
||||
}
|
||||
|
||||
if time.Now().After(sessionInfo.ExpiresAt) {
|
||||
glog.V(2).Infof("STS session has expired at %v", sessionInfo.ExpiresAt)
|
||||
return nil, nil, s3err.ErrExpiredToken
|
||||
}
|
||||
|
||||
// Validate required credential fields
|
||||
if sessionInfo.Credentials.SecretAccessKey == "" {
|
||||
glog.Warningf("STS service returned empty SecretAccessKey in credentials")
|
||||
return nil, nil, s3err.ErrInvalidAccessKeyID
|
||||
}
|
||||
|
||||
// Validate principal information
|
||||
if sessionInfo.AssumedRoleUser == "" || sessionInfo.Principal == "" {
|
||||
glog.Warningf("STS service returned empty AssumedRoleUser or Principal (user=%q, principal=%q)",
|
||||
sessionInfo.AssumedRoleUser, sessionInfo.Principal)
|
||||
return nil, nil, s3err.ErrInvalidAccessKeyID
|
||||
}
|
||||
|
||||
// Create a credential from the session info
|
||||
cred := &Credential{
|
||||
AccessKey: sessionInfo.Credentials.AccessKeyId,
|
||||
SecretKey: sessionInfo.Credentials.SecretAccessKey,
|
||||
Status: "Active",
|
||||
Expiration: sessionInfo.ExpiresAt.Unix(),
|
||||
}
|
||||
|
||||
// Create an identity for the STS session
|
||||
// The identity represents the assumed role user
|
||||
identity := &Identity{
|
||||
Name: sessionInfo.AssumedRoleUser, // Use the assumed role user as the identity name
|
||||
Account: &AccountAdmin, // STS sessions use admin account
|
||||
Credentials: []*Credential{cred},
|
||||
PrincipalArn: sessionInfo.Principal,
|
||||
}
|
||||
|
||||
glog.V(2).Infof("Successfully validated STS session token for principal: %s, assumed role user: %s",
|
||||
sessionInfo.Principal, sessionInfo.AssumedRoleUser)
|
||||
return identity, cred, s3err.ErrNone
|
||||
}
|
||||
|
||||
// calculateAndVerifySignature contains the core logic for creating the canonical request,
|
||||
// string-to-sign, and comparing the final signature.
|
||||
func calculateAndVerifySignature(secretKey, method, urlPath, queryStr string, extractedSignedHeaders http.Header, authInfo *v4AuthInfo) (string, s3err.ErrorCode) {
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// TestAuthorizeWithIAMSessionTokenExtraction tests that the authorizeWithIAM function
|
||||
// correctly extracts session tokens from multiple sources and prioritizes them appropriately.
|
||||
// This is a regression test for the bug where X-Amz-Security-Token was not being checked
|
||||
// for V4 signature authentication with STS credentials.
|
||||
func TestAuthorizeWithIAMSessionTokenExtraction(t *testing.T) {
|
||||
t.Run("Extracts X-SeaweedFS-Session-Token from JWT auth", func(t *testing.T) {
|
||||
req := &http.Request{
|
||||
Header: http.Header{
|
||||
"X-Seaweedfs-Session-Token": {"jwt-token-123"},
|
||||
"X-Seaweedfs-Principal": {"arn:aws:iam::user/test"},
|
||||
},
|
||||
URL: &url.URL{},
|
||||
}
|
||||
|
||||
// Extract tokens the same way authorizeWithIAM does
|
||||
sessionToken := req.Header.Get("X-SeaweedFS-Session-Token")
|
||||
principal := req.Header.Get("X-SeaweedFS-Principal")
|
||||
|
||||
assert.Equal(t, "jwt-token-123", sessionToken, "Should extract JWT session token from header")
|
||||
assert.Equal(t, "arn:aws:iam::user/test", principal, "Should extract principal from header")
|
||||
})
|
||||
|
||||
t.Run("Extracts X-Amz-Security-Token from V4 STS auth header", func(t *testing.T) {
|
||||
req := &http.Request{
|
||||
Header: http.Header{
|
||||
"X-Amz-Security-Token": {"sts-token-header-456"},
|
||||
},
|
||||
URL: &url.URL{},
|
||||
}
|
||||
|
||||
// Extract tokens the same way authorizeWithIAM does
|
||||
sessionToken := req.Header.Get("X-SeaweedFS-Session-Token")
|
||||
principal := req.Header.Get("X-SeaweedFS-Principal")
|
||||
|
||||
// If JWT token is empty, should fallback to X-Amz-Security-Token
|
||||
if sessionToken == "" {
|
||||
sessionToken = req.Header.Get("X-Amz-Security-Token")
|
||||
}
|
||||
|
||||
assert.Equal(t, "sts-token-header-456", sessionToken, "Should fallback to X-Amz-Security-Token when JWT token is empty")
|
||||
assert.Empty(t, principal, "JWT principal should be empty for V4 auth")
|
||||
})
|
||||
|
||||
t.Run("Extracts X-Amz-Security-Token from query parameter (presigned URL)", func(t *testing.T) {
|
||||
req := &http.Request{
|
||||
Header: http.Header{},
|
||||
URL: &url.URL{RawQuery: "X-Amz-Security-Token=sts-token-query-789"},
|
||||
}
|
||||
|
||||
// Extract tokens the same way authorizeWithIAM does
|
||||
sessionToken := req.Header.Get("X-SeaweedFS-Session-Token")
|
||||
if sessionToken == "" {
|
||||
sessionToken = req.Header.Get("X-Amz-Security-Token")
|
||||
if sessionToken == "" {
|
||||
sessionToken = req.URL.Query().Get("X-Amz-Security-Token")
|
||||
}
|
||||
}
|
||||
|
||||
assert.Equal(t, "sts-token-query-789", sessionToken, "Should extract token from query parameter")
|
||||
})
|
||||
|
||||
t.Run("JWT token takes precedence over X-Amz-Security-Token", func(t *testing.T) {
|
||||
req := &http.Request{
|
||||
Header: http.Header{
|
||||
"X-Seaweedfs-Session-Token": {"jwt-preferred"},
|
||||
"X-Seaweedfs-Principal": {"arn:aws:iam::user/jwt-user"},
|
||||
"X-Amz-Security-Token": {"sts-fallback"},
|
||||
},
|
||||
URL: &url.URL{},
|
||||
}
|
||||
|
||||
// Extract tokens the same way authorizeWithIAM does
|
||||
sessionToken := req.Header.Get("X-SeaweedFS-Session-Token")
|
||||
if sessionToken == "" {
|
||||
sessionToken = req.Header.Get("X-Amz-Security-Token")
|
||||
}
|
||||
|
||||
assert.Equal(t, "jwt-preferred", sessionToken, "JWT token should take precedence")
|
||||
})
|
||||
}
|
||||
|
||||
// TestSTSSessionTokenIntoCredentials verifies that STS session tokens are properly
|
||||
// preserved when converting to credentials for authorization.
|
||||
func TestSTSSessionTokenIntoCredentials(t *testing.T) {
|
||||
// Create a credential generator and session claims
|
||||
credGen := sts.NewCredentialGenerator()
|
||||
sessionId := "test-session-123"
|
||||
expiresAt := time.Now().Add(time.Hour)
|
||||
|
||||
// Generate temporary credentials
|
||||
creds, err := credGen.GenerateTemporaryCredentials(sessionId, expiresAt)
|
||||
require.NoError(t, err, "Should generate credentials successfully")
|
||||
require.NotNil(t, creds, "Credentials should not be nil")
|
||||
|
||||
// Verify all credential fields are present
|
||||
assert.NotEmpty(t, creds.AccessKeyId, "AccessKeyId should be present")
|
||||
assert.NotEmpty(t, creds.SecretAccessKey, "SecretAccessKey should be present")
|
||||
assert.NotEmpty(t, creds.SessionToken, "SessionToken should be present for STS")
|
||||
|
||||
// Verify deterministic generation (same session ID produces same credentials)
|
||||
creds2, err := credGen.GenerateTemporaryCredentials(sessionId, expiresAt)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, creds.AccessKeyId, creds2.AccessKeyId, "AccessKeyId should be deterministic")
|
||||
assert.Equal(t, creds.SecretAccessKey, creds2.SecretAccessKey, "SecretAccessKey should be deterministic")
|
||||
assert.Equal(t, creds.SessionToken, creds2.SessionToken, "SessionToken should be deterministic for same sessionId")
|
||||
|
||||
// Verify different session produces different credentials
|
||||
creds3, err := credGen.GenerateTemporaryCredentials("different-session", expiresAt)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.NotEqual(t, creds.AccessKeyId, creds3.AccessKeyId, "Different sessions should produce different access key IDs")
|
||||
assert.NotEqual(t, creds.SecretAccessKey, creds3.SecretAccessKey, "Different sessions should produce different secret keys")
|
||||
assert.NotEqual(t, creds.SessionToken, creds3.SessionToken, "Different sessions should produce different session tokens")
|
||||
}
|
||||
|
||||
// TestActionConstantsForV4Auth verifies that action constants are properly available
|
||||
// for use in authorization checks with V4 signature authentication.
|
||||
func TestActionConstantsForV4Auth(t *testing.T) {
|
||||
// Verify that S3 action constants are available
|
||||
actions := map[string]string{
|
||||
"READ": s3_constants.ACTION_READ,
|
||||
"WRITE": s3_constants.ACTION_WRITE,
|
||||
"READ_ACP": s3_constants.ACTION_READ_ACP,
|
||||
"WRITE_ACP": s3_constants.ACTION_WRITE_ACP,
|
||||
"LIST": s3_constants.ACTION_LIST,
|
||||
"TAGGING": s3_constants.ACTION_TAGGING,
|
||||
"ADMIN": s3_constants.ACTION_ADMIN,
|
||||
}
|
||||
|
||||
for name, action := range actions {
|
||||
assert.NotEmpty(t, action, "Action %s should not be empty", name)
|
||||
}
|
||||
}
|
||||
@@ -770,7 +770,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
err = s3a.streamFromVolumeServersWithSSE(w, r, objectEntryForSSE, primarySSEType, bucket, object, versionId)
|
||||
streamTime = time.Since(tStream)
|
||||
if err != nil {
|
||||
glog.Errorf("GetObjectHandler: failed to stream %s/%s from volume servers: %v", bucket, object, err)
|
||||
glog.Errorf("GetObjectHandler: failed to stream from volume servers: %v", err)
|
||||
// Check if the streaming function already wrote an HTTP response
|
||||
var streamErr *StreamError
|
||||
if errors.As(err, &streamErr) && streamErr.ResponseWritten {
|
||||
@@ -875,7 +875,7 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R
|
||||
// Set header BEFORE WriteHeader
|
||||
w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", totalSize))
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRange)
|
||||
return newStreamErrorWithResponse(fmt.Errorf("invalid range start for %s/%s: %d >= %d, range: %s", bucket, object, startOffset, totalSize, rangeHeader))
|
||||
return newStreamErrorWithResponse(fmt.Errorf("invalid range start"))
|
||||
}
|
||||
|
||||
if endOffset >= totalSize {
|
||||
@@ -1156,7 +1156,7 @@ func (s3a *S3ApiServer) streamFromVolumeServersWithSSE(w http.ResponseWriter, r
|
||||
// Set header BEFORE WriteHeader
|
||||
w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", totalSize))
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRange)
|
||||
return newStreamErrorWithResponse(fmt.Errorf("invalid range start for %s/%s: %d >= %d, range: %s", bucket, object, startOffset, totalSize, rangeHeader))
|
||||
return newStreamErrorWithResponse(fmt.Errorf("invalid range start"))
|
||||
}
|
||||
|
||||
if endOffset >= totalSize {
|
||||
|
||||
@@ -55,7 +55,7 @@ func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Requ
|
||||
bucket, _ := s3_constants.GetBucketAndObject(r)
|
||||
originalPrefix, startAfter, delimiter, continuationToken, encodingTypeUrl, fetchOwner, maxKeys, allowUnordered, errCode := getListObjectsV2Args(r.URL.Query())
|
||||
|
||||
glog.V(2).Infof("ListObjectsV2Handler bucket=%s prefix=%s marker=%s", bucket, originalPrefix, continuationToken.string)
|
||||
glog.V(2).Infof("ListObjectsV2Handler bucket=%s prefix=%s", bucket, originalPrefix)
|
||||
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
@@ -120,7 +120,7 @@ func (s3a *S3ApiServer) ListObjectsV1Handler(w http.ResponseWriter, r *http.Requ
|
||||
bucket, _ := s3_constants.GetBucketAndObject(r)
|
||||
originalPrefix, marker, delimiter, encodingTypeUrl, maxKeys, allowUnordered, errCode := getListObjectsV1Args(r.URL.Query())
|
||||
|
||||
glog.V(2).Infof("ListObjectsV1Handler bucket=%s prefix=%s marker=%s delimiter=%s maxKeys=%d", bucket, originalPrefix, marker, delimiter, maxKeys)
|
||||
glog.V(2).Infof("ListObjectsV1Handler bucket=%s prefix=%s delimiter=%s maxKeys=%d", bucket, originalPrefix, delimiter, maxKeys)
|
||||
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
@@ -257,7 +257,7 @@ func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, m
|
||||
cursor.maxKeys--
|
||||
lastEntryWasCommonPrefix = false
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
|
||||
} else if delimiter != "" { // A response can contain CommonPrefixes only if you specify a delimiter.
|
||||
} else if delimiter == "/" { // A response can contain CommonPrefixes only if you specify a delimiter.
|
||||
// Use raw dir and entry.Name (not encoded) to ensure consistent handling
|
||||
// Encoding will be applied after sorting if encodingTypeUrl is set
|
||||
commonPrefixes = append(commonPrefixes, PrefixEntry{
|
||||
@@ -742,7 +742,7 @@ func adjustMarkerForDelimiter(marker, delimiter string) string {
|
||||
return marker
|
||||
}
|
||||
|
||||
// Remove the trailing delimiter
|
||||
// Remove the trailing delimiter and append a high ASCII character
|
||||
// This ensures we skip all entries under the prefix but don't skip
|
||||
// potential directory entries that start with a similar prefix
|
||||
prefix := strings.TrimSuffix(marker, delimiter)
|
||||
@@ -750,5 +750,7 @@ func adjustMarkerForDelimiter(marker, delimiter string) string {
|
||||
return marker
|
||||
}
|
||||
|
||||
return prefix
|
||||
// Use tilde (~) which has ASCII value 126, higher than most printable characters
|
||||
// This skips "prefix/*" entries but still finds "prefix" + any higher character
|
||||
return prefix + "~"
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// TestDirectoryListedAsCommonPrefix tests that regular directories (without MIME)
|
||||
// are correctly listed as CommonPrefixes when delimiter="/" is used, not as objects.
|
||||
// Note: The fix applies to any non-empty delimiter ('/', '_', ':'), but this test focuses on '/'.
|
||||
func TestDirectoryListedAsCommonPrefix(t *testing.T) {
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{
|
||||
BucketsPath: "/buckets",
|
||||
},
|
||||
}
|
||||
|
||||
// Regular directory (no MIME) - matching actual user metadata
|
||||
regularDir := &filer_pb.Entry{
|
||||
Name: "f2f1237f-0e69-4e0b-8f01-d4fa299787e1.vhd",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mime: "", // Empty MIME - IsDirectoryKeyObject() returns false
|
||||
},
|
||||
}
|
||||
|
||||
client := &testFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/xoa-bucket/xo-vm-backups/data": {regularDir},
|
||||
},
|
||||
}
|
||||
|
||||
cursor := &ListingCursor{maxKeys: 1000}
|
||||
var seenDirs []string
|
||||
var seenFiles []string
|
||||
|
||||
_, err := s3a.doListFilerEntries(
|
||||
client,
|
||||
"/buckets/xoa-bucket/xo-vm-backups/data",
|
||||
"", // prefix
|
||||
cursor,
|
||||
"", // marker
|
||||
"/", // delimiter="/" - should yield directory for CommonPrefix processing
|
||||
false,
|
||||
"xoa-bucket",
|
||||
func(dir string, entry *filer_pb.Entry) {
|
||||
if entry.IsDirectory {
|
||||
seenDirs = append(seenDirs, entry.Name)
|
||||
} else {
|
||||
seenFiles = append(seenFiles, entry.Name)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
assert.NoError(t, err)
|
||||
|
||||
// The directory should be passed to the callback for delimiter="/"
|
||||
assert.Contains(t, seenDirs, "f2f1237f-0e69-4e0b-8f01-d4fa299787e1.vhd",
|
||||
"Directory should be passed to callback for CommonPrefix processing with delimiter=/")
|
||||
assert.Empty(t, seenFiles, "No files should be seen, only the directory")
|
||||
}
|
||||
@@ -95,7 +95,6 @@ const (
|
||||
ErrInvalidQueryParams
|
||||
ErrInvalidQuerySignatureAlgo
|
||||
ErrExpiredPresignRequest
|
||||
ErrExpiredToken
|
||||
ErrMalformedExpires
|
||||
ErrNegativeExpires
|
||||
ErrMaximumExpires
|
||||
@@ -406,11 +405,6 @@ var errorCodeResponse = map[ErrorCode]APIError{
|
||||
Description: "Request has expired",
|
||||
HTTPStatusCode: http.StatusForbidden,
|
||||
},
|
||||
ErrExpiredToken: {
|
||||
Code: "ExpiredToken",
|
||||
Description: "The provided token has expired.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
ErrMalformedExpires: {
|
||||
Code: "AuthorizationQueryParametersError",
|
||||
Description: "X-Amz-Expires should be a number",
|
||||
|
||||
@@ -275,16 +275,16 @@ func writeECShardInformationMessage(writer io.Writer, t *master_pb.VolumeEcShard
|
||||
var shardDetails []string
|
||||
for _, shardId := range si.Ids() {
|
||||
size := uint64(si.Size(shardId))
|
||||
shardDetails = append(shardDetails, fmt.Sprintf("%d:%s", shardId, util.BytesToHumanReadable(uint64(size))))
|
||||
shardDetails = append(shardDetails, fmt.Sprintf("%d:%s", shardId, util.BytesToHumanReadable(size)))
|
||||
totalSize += size
|
||||
}
|
||||
shardSizeInfo = fmt.Sprintf(" sizes:[%s] total:%s", strings.Join(shardDetails, " "), util.BytesToHumanReadable(uint64(totalSize)))
|
||||
shardSizeInfo = fmt.Sprintf(" sizes:[%s] total:%s", strings.Join(shardDetails, " "), util.BytesToHumanReadable(totalSize))
|
||||
}
|
||||
|
||||
output(verbosityLevel >= 5, writer, " ec volume id:%v collection:%v shards:%v%s %s\n",
|
||||
t.Id, t.Collection, si.Ids(), shardSizeInfo, expireAtString)
|
||||
|
||||
// TODO: add file counts once available in VolumeInformationMessage.
|
||||
// TODO: add file counts once available in VolumeEcShardInformationMessage.
|
||||
return statistics{
|
||||
Size: totalSize,
|
||||
}
|
||||
@@ -304,12 +304,7 @@ type statistics struct {
|
||||
}
|
||||
|
||||
func newStatistics() *statistics {
|
||||
return &statistics{
|
||||
Size: 0,
|
||||
FileCount: 0,
|
||||
DeletedFileCount: 0,
|
||||
DeletedBytes: 0,
|
||||
}
|
||||
return &statistics{}
|
||||
}
|
||||
|
||||
func (s *statistics) add(t statistics) {
|
||||
|
||||
@@ -34,8 +34,6 @@ type DiskLocation struct {
|
||||
ecVolumes map[needle.VolumeId]*erasure_coding.EcVolume
|
||||
ecVolumesLock sync.RWMutex
|
||||
|
||||
ecShardNotifyHandler func(collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, ecVolume *erasure_coding.EcVolume)
|
||||
|
||||
isDiskSpaceLow bool
|
||||
closeCh chan struct{}
|
||||
}
|
||||
@@ -261,7 +259,7 @@ func (l *DiskLocation) loadExistingVolumesWithId(needleMapKind NeedleMapKind, ld
|
||||
l.concurrentLoadingVolumes(needleMapKind, workerNum, ldbTimeout, diskId)
|
||||
glog.V(2).Infof("Store started on dir: %s with %d volumes max %d (disk ID: %d)", l.Directory, len(l.volumes), l.MaxVolumeCount, diskId)
|
||||
|
||||
l.loadAllEcShards(l.ecShardNotifyHandler)
|
||||
l.loadAllEcShards()
|
||||
glog.V(2).Infof("Store started on dir: %s with %d ec shards (disk ID: %d)", l.Directory, len(l.ecVolumes), diskId)
|
||||
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ func (l *DiskLocation) UnloadEcShard(vid needle.VolumeId, shardId erasure_coding
|
||||
return true
|
||||
}
|
||||
|
||||
func (l *DiskLocation) loadEcShards(shards []string, collection string, vid needle.VolumeId, onShardLoad func(collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, ecVolume *erasure_coding.EcVolume)) (err error) {
|
||||
func (l *DiskLocation) loadEcShards(shards []string, collection string, vid needle.VolumeId) (err error) {
|
||||
|
||||
for _, shard := range shards {
|
||||
shardId, err := strconv.ParseInt(path.Ext(shard)[3:], 10, 64)
|
||||
@@ -149,19 +149,16 @@ func (l *DiskLocation) loadEcShards(shards []string, collection string, vid need
|
||||
return fmt.Errorf("shard ID out of range: %d", shardId)
|
||||
}
|
||||
|
||||
ecVolume, err := l.LoadEcShard(collection, vid, erasure_coding.ShardId(shardId))
|
||||
_, err = l.LoadEcShard(collection, vid, erasure_coding.ShardId(shardId))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load ec shard %v: %w", shard, err)
|
||||
}
|
||||
if onShardLoad != nil {
|
||||
onShardLoad(collection, vid, erasure_coding.ShardId(shardId), ecVolume)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *DiskLocation) loadAllEcShards(onShardLoad func(collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, ecVolume *erasure_coding.EcVolume)) (err error) {
|
||||
func (l *DiskLocation) loadAllEcShards() (err error) {
|
||||
|
||||
dirEntries, err := os.ReadDir(l.Directory)
|
||||
if err != nil {
|
||||
@@ -225,7 +222,7 @@ func (l *DiskLocation) loadAllEcShards(onShardLoad func(collection string, vid n
|
||||
}
|
||||
|
||||
if ext == ".ecx" && volumeId == prevVolumeId && collection == prevCollection {
|
||||
l.handleFoundEcxFile(sameVolumeShards, collection, volumeId, onShardLoad)
|
||||
l.handleFoundEcxFile(sameVolumeShards, collection, volumeId)
|
||||
reset()
|
||||
continue
|
||||
}
|
||||
@@ -280,7 +277,7 @@ func (l *DiskLocation) EcShardCount() int {
|
||||
|
||||
// handleFoundEcxFile processes a complete group of EC shards when their .ecx file is found.
|
||||
// This includes validation, loading, and cleanup of incomplete/invalid EC volumes.
|
||||
func (l *DiskLocation) handleFoundEcxFile(shards []string, collection string, volumeId needle.VolumeId, onShardLoad func(collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, ecVolume *erasure_coding.EcVolume)) {
|
||||
func (l *DiskLocation) handleFoundEcxFile(shards []string, collection string, volumeId needle.VolumeId) {
|
||||
// Check if this is an incomplete EC encoding (not a distributed EC volume)
|
||||
// Key distinction: if .dat file still exists, EC encoding may have failed
|
||||
// If .dat file is gone, this is likely a distributed EC volume with shards on multiple servers
|
||||
@@ -300,7 +297,7 @@ func (l *DiskLocation) handleFoundEcxFile(shards []string, collection string, vo
|
||||
}
|
||||
|
||||
// Attempt to load the EC shards
|
||||
if err := l.loadEcShards(shards, collection, volumeId, onShardLoad); err != nil {
|
||||
if err := l.loadEcShards(shards, collection, volumeId); err != nil {
|
||||
// If EC shards failed to load and .dat still exists, clean up EC files to allow .dat file to be used
|
||||
// If .dat is gone, log error but don't clean up (may be waiting for shards from other servers)
|
||||
if datExists {
|
||||
|
||||
@@ -177,13 +177,13 @@ func TestIncompleteEcEncodingCleanup(t *testing.T) {
|
||||
}
|
||||
|
||||
// Run loadAllEcShards
|
||||
loadErr := diskLocation.loadAllEcShards(nil)
|
||||
loadErr := diskLocation.loadAllEcShards()
|
||||
if loadErr != nil {
|
||||
t.Logf("loadAllEcShards returned error (expected in some cases): %v", loadErr)
|
||||
}
|
||||
|
||||
// Test idempotency - running again should not cause issues
|
||||
loadErr2 := diskLocation.loadAllEcShards(nil)
|
||||
loadErr2 := diskLocation.loadAllEcShards()
|
||||
if loadErr2 != nil {
|
||||
t.Logf("Second loadAllEcShards returned error: %v", loadErr2)
|
||||
}
|
||||
@@ -550,7 +550,7 @@ func TestEcCleanupWithSeparateIdxDirectory(t *testing.T) {
|
||||
// Do not create .ecx: trigger orphaned-shards cleanup when .dat exists
|
||||
|
||||
// Run loadAllEcShards
|
||||
loadErr := diskLocation.loadAllEcShards(nil)
|
||||
loadErr := diskLocation.loadAllEcShards()
|
||||
if loadErr != nil {
|
||||
t.Logf("loadAllEcShards error: %v", loadErr)
|
||||
}
|
||||
@@ -621,7 +621,7 @@ func TestDistributedEcVolumeNoFileDeletion(t *testing.T) {
|
||||
// NO .dat file - this is a distributed EC volume
|
||||
|
||||
// Run loadAllEcShards - this should fail but NOT delete shard files
|
||||
loadErr := diskLocation.loadAllEcShards(nil)
|
||||
loadErr := diskLocation.loadAllEcShards()
|
||||
if loadErr != nil {
|
||||
t.Logf("loadAllEcShards returned error (expected): %v", loadErr)
|
||||
}
|
||||
|
||||
+6
-33
@@ -86,12 +86,6 @@ func NewStore(grpcDialOption grpc.DialOption, ip string, port int, grpcPort int,
|
||||
s = &Store{grpcDialOption: grpcDialOption, Port: port, Ip: ip, GrpcPort: grpcPort, PublicUrl: publicUrl, Id: id, NeedleMapKind: needleMapKind}
|
||||
s.Locations = make([]*DiskLocation, 0)
|
||||
|
||||
s.NewVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 1024)
|
||||
s.DeletedVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 1024)
|
||||
|
||||
s.NewEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 1024)
|
||||
s.DeletedEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 1024)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < len(dirnames); i++ {
|
||||
location := NewDiskLocation(dirnames[i], int32(maxVolumeCounts[i]), minFreeSpaces[i], idxFolder, diskTypes[i])
|
||||
@@ -99,33 +93,6 @@ func NewStore(grpcDialOption grpc.DialOption, ip string, port int, grpcPort int,
|
||||
stats.VolumeServerMaxVolumeCounter.Add(float64(maxVolumeCounts[i]))
|
||||
|
||||
diskId := uint32(i) // Track disk ID
|
||||
|
||||
location.ecShardNotifyHandler = func(collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, ecVolume *erasure_coding.EcVolume) {
|
||||
var shardSize int64
|
||||
if shard, found := ecVolume.FindEcVolumeShard(shardId); found {
|
||||
shardSize = shard.Size()
|
||||
}
|
||||
si := erasure_coding.NewShardsInfo()
|
||||
si.Set(shardId, erasure_coding.ShardSize(shardSize))
|
||||
|
||||
// Use non-blocking send during startup to avoid deadlock
|
||||
// The channel reader only starts after connecting to master, but we're loading during startup
|
||||
select {
|
||||
case s.NewEcShardsChan <- master_pb.VolumeEcShardInformationMessage{
|
||||
Id: uint32(vid),
|
||||
Collection: collection,
|
||||
EcIndexBits: si.Bitmap(),
|
||||
ShardSizes: si.SizesInt64(),
|
||||
DiskType: string(location.DiskType),
|
||||
ExpireAtSec: ecVolume.ExpireAtSec,
|
||||
DiskId: diskId,
|
||||
}:
|
||||
default:
|
||||
// Channel full during startup - this is OK, heartbeat will report EC shards later
|
||||
glog.V(2).Infof("NewEcShardsChan full during startup for shard %d.%d, will be reported in heartbeat", vid, shardId)
|
||||
}
|
||||
}
|
||||
|
||||
wg.Add(1)
|
||||
go func(id uint32, diskLoc *DiskLocation) {
|
||||
defer wg.Done()
|
||||
@@ -134,6 +101,12 @@ func NewStore(grpcDialOption grpc.DialOption, ip string, port int, grpcPort int,
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
s.NewVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 3)
|
||||
s.DeletedVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 3)
|
||||
|
||||
s.NewEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 3)
|
||||
s.DeletedEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 3)
|
||||
|
||||
return
|
||||
}
|
||||
func (s *Store) AddVolume(volumeId needle.VolumeId, collection string, needleMapKind NeedleMapKind, replicaPlacement string, ttlString string, preallocate int64, ver needle.Version, MemoryMapMaxSizeMb uint32, diskType DiskType, ldbTimeout int64) error {
|
||||
|
||||
+1
-1
@@ -67,7 +67,7 @@ func RetryUntil(name string, job func() error, onErrFn func(err error) (shouldCo
|
||||
break
|
||||
}
|
||||
if onErrFn(err) {
|
||||
if strings.Contains(err.Error(), "transport") || strings.Contains(err.Error(), "ResourceExhausted") || strings.Contains(err.Error(), "Unavailable") {
|
||||
if strings.Contains(err.Error(), "transport") {
|
||||
glog.V(0).Infof("retry %s: err: %v", name, err)
|
||||
}
|
||||
time.Sleep(waitTime)
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
var (
|
||||
MAJOR_VERSION = int32(4)
|
||||
MINOR_VERSION = int32(05)
|
||||
MINOR_VERSION = int32(04)
|
||||
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
|
||||
VERSION = util.SizeLimit + " " + VERSION_NUMBER
|
||||
COMMIT = ""
|
||||
|
||||
+46
-93
@@ -7,8 +7,6 @@ import (
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"crypto/rand"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
@@ -28,9 +26,6 @@ type GrpcAdminClient struct {
|
||||
|
||||
cmds chan grpcCommand
|
||||
|
||||
// Session identification for logging
|
||||
sessionID string
|
||||
|
||||
// Reconnection parameters
|
||||
maxReconnectAttempts int
|
||||
reconnectBackoff time.Duration
|
||||
@@ -54,7 +49,6 @@ const (
|
||||
ActionQueryReconnecting grpcAction = "query_reconnecting"
|
||||
ActionQueryConnected grpcAction = "query_connected"
|
||||
ActionQueryShouldReconnect grpcAction = "query_shouldreconnect"
|
||||
ActionResetReconnectStop grpcAction = "reset_reconnect_stop"
|
||||
)
|
||||
|
||||
type registrationRequest struct {
|
||||
@@ -89,15 +83,9 @@ func NewGrpcAdminClient(adminAddress string, workerID string, dialOption grpc.Di
|
||||
// Admin uses HTTP port + 10000 as gRPC port
|
||||
grpcAddress := pb.ServerToGrpcAddress(adminAddress)
|
||||
|
||||
// Generate a unique session ID for logging
|
||||
sessionBytes := make([]byte, 2)
|
||||
rand.Read(sessionBytes)
|
||||
sessionID := fmt.Sprintf("%x", sessionBytes)
|
||||
|
||||
c := &GrpcAdminClient{
|
||||
adminAddress: grpcAddress,
|
||||
workerID: workerID,
|
||||
sessionID: sessionID,
|
||||
dialOption: dialOption,
|
||||
maxReconnectAttempts: 0, // 0 means infinite attempts
|
||||
reconnectBackoff: 1 * time.Second,
|
||||
@@ -145,11 +133,8 @@ func (c *GrpcAdminClient) safeCloseChannel(chPtr *chan struct{}) {
|
||||
func (c *GrpcAdminClient) managerLoop() {
|
||||
state := &grpcState{shouldReconnect: true}
|
||||
|
||||
glog.V(1).Infof("[session %s] Manager loop started for worker %s", c.sessionID, c.workerID)
|
||||
|
||||
out:
|
||||
for cmd := range c.cmds {
|
||||
glog.V(4).Infof("[session %s] Manager received command: %s", c.sessionID, cmd.action)
|
||||
switch cmd.action {
|
||||
case ActionConnect:
|
||||
c.handleConnect(cmd, state)
|
||||
@@ -167,20 +152,11 @@ out:
|
||||
cmd.resp <- err
|
||||
case ActionStreamError:
|
||||
state.connected = false
|
||||
// Restart reconnection loop if needed
|
||||
if state.shouldReconnect && state.reconnectStop == nil {
|
||||
glog.V(1).Infof("[session %s] Stream error, starting reconnection loop", c.sessionID)
|
||||
stop := make(chan struct{})
|
||||
state.reconnectStop = stop
|
||||
go c.reconnectionLoop(stop, func() {
|
||||
c.cmds <- grpcCommand{action: ActionResetReconnectStop, data: state}
|
||||
})
|
||||
}
|
||||
case ActionRegisterWorker:
|
||||
req := cmd.data.(registrationRequest)
|
||||
state.lastWorkerInfo = req.Worker
|
||||
if !state.connected {
|
||||
glog.V(1).Infof("[session %s] Not connected yet, worker info stored for registration upon connection", c.sessionID)
|
||||
glog.V(1).Infof("Not connected yet, worker info stored for registration upon connection")
|
||||
// Respond immediately with success (registration will happen later)
|
||||
req.Resp <- nil
|
||||
continue
|
||||
@@ -203,17 +179,13 @@ out:
|
||||
case ActionQueryShouldReconnect:
|
||||
respCh := cmd.data.(chan bool)
|
||||
respCh <- state.shouldReconnect
|
||||
case ActionResetReconnectStop:
|
||||
// This is an internal action to reset the stop channel when reconnectionLoop exits
|
||||
s := cmd.data.(*grpcState)
|
||||
s.reconnectStop = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Connect establishes gRPC connection to admin server with TLS detection
|
||||
func (c *GrpcAdminClient) Connect() error {
|
||||
resp := make(chan error, 1)
|
||||
resp := make(chan error)
|
||||
c.cmds <- grpcCommand{
|
||||
action: ActionConnect,
|
||||
resp: resp,
|
||||
@@ -227,24 +199,15 @@ func (c *GrpcAdminClient) handleConnect(cmd grpcCommand, s *grpcState) {
|
||||
return
|
||||
}
|
||||
|
||||
// Start reconnection loop immediately if not already running (async)
|
||||
if s.reconnectStop == nil {
|
||||
glog.V(1).Infof("[session %s] Starting reconnection loop", c.sessionID)
|
||||
stop := make(chan struct{})
|
||||
s.reconnectStop = stop
|
||||
go c.reconnectionLoop(stop, func() {
|
||||
// This callback is executed when the reconnectionLoop exits.
|
||||
// It ensures that s.reconnectStop is reset to nil, allowing a new loop to be started later.
|
||||
c.cmds <- grpcCommand{action: ActionResetReconnectStop, data: s}
|
||||
})
|
||||
} else {
|
||||
glog.V(1).Infof("[session %s] Reconnection loop already running", c.sessionID)
|
||||
}
|
||||
// Start reconnection loop immediately (async)
|
||||
stop := make(chan struct{})
|
||||
s.reconnectStop = stop
|
||||
go c.reconnectionLoop(stop)
|
||||
|
||||
// Attempt the initial connection
|
||||
err := c.attemptConnection(s)
|
||||
if err != nil {
|
||||
glog.Warningf("[session %s] Initial connection failed, reconnection loop will retry: %v", c.sessionID, err)
|
||||
glog.V(1).Infof("Initial connection failed, reconnection loop will retry: %v", err)
|
||||
cmd.resp <- err
|
||||
return
|
||||
}
|
||||
@@ -258,10 +221,10 @@ func (c *GrpcAdminClient) createConnection() (*grpc.ClientConn, error) {
|
||||
|
||||
conn, err := pb.GrpcDial(ctx, c.adminAddress, false, c.dialOption)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect to admin server %s: %w", c.adminAddress, err)
|
||||
return nil, fmt.Errorf("failed to connect to admin server: %w", err)
|
||||
}
|
||||
|
||||
glog.Infof("[session %s] Connected to admin server at %s", c.sessionID, c.adminAddress)
|
||||
glog.Infof("Connected to admin server at %s", c.adminAddress)
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
@@ -279,7 +242,7 @@ func (c *GrpcAdminClient) attemptConnection(s *grpcState) error {
|
||||
// Create bidirectional stream
|
||||
s.streamCtx, s.streamCancel = context.WithCancel(context.Background())
|
||||
stream, err := s.client.WorkerStream(s.streamCtx)
|
||||
glog.Infof("[session %s] Worker stream created", c.sessionID)
|
||||
glog.Infof("Worker stream created")
|
||||
if err != nil {
|
||||
s.conn.Close()
|
||||
return fmt.Errorf("failed to create worker stream: %w", err)
|
||||
@@ -292,8 +255,8 @@ func (c *GrpcAdminClient) attemptConnection(s *grpcState) error {
|
||||
s.streamExit = make(chan struct{})
|
||||
s.streamFailed = make(chan struct{})
|
||||
s.regWait = make(chan *worker_pb.RegistrationResponse, 1)
|
||||
go handleOutgoing(c.sessionID, s.stream, s.streamExit, c.outgoing, c.cmds)
|
||||
go handleIncoming(c.sessionID, c.workerID, s.stream, s.streamExit, c.incoming, c.cmds, s.streamFailed, s.regWait)
|
||||
go handleOutgoing(s.stream, s.streamExit, c.outgoing, c.cmds)
|
||||
go handleIncoming(c.workerID, s.stream, s.streamExit, c.incoming, c.cmds, s.streamFailed, s.regWait)
|
||||
|
||||
// Always check for worker info and send registration immediately as the very first message
|
||||
if s.lastWorkerInfo != nil {
|
||||
@@ -307,19 +270,18 @@ func (c *GrpcAdminClient) attemptConnection(s *grpcState) error {
|
||||
s.connected = false
|
||||
return fmt.Errorf("failed to register worker: %w", err)
|
||||
}
|
||||
glog.Infof("[session %s] Worker %s registered successfully with admin server", c.sessionID, c.workerID)
|
||||
glog.Infof("Worker registered successfully with admin server")
|
||||
} else {
|
||||
// No worker info yet - stream will wait for registration
|
||||
glog.V(1).Infof("[session %s] Connected to admin server, waiting for worker registration info", c.sessionID)
|
||||
glog.V(1).Infof("Connected to admin server, waiting for worker registration info")
|
||||
}
|
||||
|
||||
glog.V(1).Infof("[session %s] attemptConnection successful", c.sessionID)
|
||||
glog.Infof("Connected to admin server at %s", c.adminAddress)
|
||||
return nil
|
||||
}
|
||||
|
||||
// reconnect attempts to re-establish the connection
|
||||
func (c *GrpcAdminClient) reconnect(s *grpcState) error {
|
||||
glog.V(1).Infof("[session %s] Reconnection attempt starting", c.sessionID)
|
||||
// Clean up existing connection completely
|
||||
c.safeCloseChannel(&s.streamExit)
|
||||
c.safeCloseChannel(&s.streamFailed)
|
||||
@@ -337,31 +299,25 @@ func (c *GrpcAdminClient) reconnect(s *grpcState) error {
|
||||
return fmt.Errorf("failed to reconnect: %w", err)
|
||||
}
|
||||
|
||||
glog.Infof("[session %s] Successfully reconnected to admin server", c.sessionID)
|
||||
// Registration is now handled in attemptConnection if worker info is available
|
||||
return nil
|
||||
}
|
||||
|
||||
// reconnectionLoop handles automatic reconnection with exponential backoff
|
||||
func (c *GrpcAdminClient) reconnectionLoop(reconnectStop chan struct{}, onExit func()) {
|
||||
defer onExit() // Ensure the cleanup callback is called when the loop exits
|
||||
func (c *GrpcAdminClient) reconnectionLoop(reconnectStop chan struct{}) {
|
||||
backoff := c.reconnectBackoff
|
||||
attempts := 0
|
||||
|
||||
for {
|
||||
attempts++ // Count this attempt (starts at 1)
|
||||
waitDuration := backoff
|
||||
if attempts == 1 {
|
||||
waitDuration = 100 * time.Millisecond // Quick retry for the very first failure
|
||||
if attempts == 0 {
|
||||
waitDuration = time.Second
|
||||
}
|
||||
glog.V(2).Infof("[session %s] Reconnection loop sleeping for %v before attempt %d", c.sessionID, waitDuration, attempts)
|
||||
select {
|
||||
case <-reconnectStop:
|
||||
glog.V(1).Infof("[session %s] Reconnection loop stopping (received signal)", c.sessionID)
|
||||
return
|
||||
case <-time.After(waitDuration):
|
||||
}
|
||||
|
||||
resp := make(chan error, 1)
|
||||
c.cmds <- grpcCommand{
|
||||
action: ActionReconnect,
|
||||
@@ -370,17 +326,19 @@ func (c *GrpcAdminClient) reconnectionLoop(reconnectStop chan struct{}, onExit f
|
||||
err := <-resp
|
||||
if err == nil {
|
||||
// Successful reconnection
|
||||
glog.Infof("[session %s] Successfully reconnected to admin server, stopping reconnection loop", c.sessionID)
|
||||
return // EXIT ON SUCCESS
|
||||
attempts = 0
|
||||
backoff = c.reconnectBackoff
|
||||
glog.Infof("Successfully reconnected to admin server")
|
||||
} else if errors.Is(err, ErrAlreadyConnected) {
|
||||
glog.V(1).Infof("[session %s] Already connected, stopping reconnection loop", c.sessionID)
|
||||
return // EXIT ON SUCCESS (already connected)
|
||||
attempts = 0
|
||||
backoff = c.reconnectBackoff
|
||||
} else {
|
||||
glog.Warningf("[session %s] Reconnection attempt %d failed: %v", c.sessionID, attempts, err)
|
||||
attempts++
|
||||
glog.Errorf("Reconnection attempt %d failed: %v", attempts, err)
|
||||
|
||||
// Check if we should give up
|
||||
if c.maxReconnectAttempts > 0 && attempts >= c.maxReconnectAttempts {
|
||||
glog.Errorf("[session %s] Max reconnection attempts (%d) reached, giving up", c.sessionID, c.maxReconnectAttempts)
|
||||
glog.Errorf("Max reconnection attempts (%d) reached, giving up", c.maxReconnectAttempts)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -389,21 +347,17 @@ func (c *GrpcAdminClient) reconnectionLoop(reconnectStop chan struct{}, onExit f
|
||||
if backoff > c.maxReconnectBackoff {
|
||||
backoff = c.maxReconnectBackoff
|
||||
}
|
||||
glog.V(1).Infof("[session %s] Waiting %v before next reconnection attempt", c.sessionID, backoff)
|
||||
glog.Infof("Waiting %v before next reconnection attempt", backoff)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleOutgoing processes outgoing messages to admin
|
||||
func handleOutgoing(
|
||||
sessionID string,
|
||||
stream worker_pb.WorkerService_WorkerStreamClient,
|
||||
streamExit <-chan struct{},
|
||||
outgoing <-chan *worker_pb.WorkerMessage,
|
||||
cmds chan<- grpcCommand) {
|
||||
|
||||
glog.V(1).Infof("[session %s] Outgoing message handler started", sessionID)
|
||||
defer glog.V(1).Infof("[session %s] Outgoing message handler stopping", sessionID)
|
||||
msgCh := make(chan *worker_pb.WorkerMessage, 1)
|
||||
errCh := make(chan error, 1) // Buffered to prevent blocking if the manager is busy
|
||||
|
||||
@@ -421,18 +375,18 @@ func handleOutgoing(
|
||||
// Helper function to handle stream errors and cleanup
|
||||
handleStreamError := func(err error) {
|
||||
if err != nil {
|
||||
glog.Warningf("[session %s] Stream send error: %v", sessionID, err)
|
||||
glog.Errorf("Failed to send message to admin: %v", err)
|
||||
select {
|
||||
case cmds <- grpcCommand{action: ActionStreamError, data: err}:
|
||||
// Successfully queued
|
||||
default:
|
||||
// Manager busy, queue asynchronously to avoid blocking
|
||||
glog.V(2).Infof("[session %s] Manager busy, queuing stream error asynchronously from outgoing handler: %v", sessionID, err)
|
||||
glog.V(2).Infof("Manager busy, queuing stream error asynchronously from outgoing handler: %v", err)
|
||||
go func(e error) {
|
||||
select {
|
||||
case cmds <- grpcCommand{action: ActionStreamError, data: e}:
|
||||
case <-time.After(2 * time.Second):
|
||||
glog.Warningf("[session %s] Failed to send stream error to manager from outgoing handler, channel blocked: %v", sessionID, e)
|
||||
glog.Warningf("Failed to send stream error to manager from outgoing handler, channel blocked: %v", e)
|
||||
}
|
||||
}(err)
|
||||
}
|
||||
@@ -474,17 +428,14 @@ func handleOutgoing(
|
||||
|
||||
// handleIncoming processes incoming messages from admin
|
||||
func handleIncoming(
|
||||
sessionID string,
|
||||
workerID string,
|
||||
stream worker_pb.WorkerService_WorkerStreamClient,
|
||||
streamExit <-chan struct{},
|
||||
incoming chan<- *worker_pb.AdminMessage,
|
||||
cmds chan<- grpcCommand,
|
||||
streamFailed chan struct{},
|
||||
regWait chan *worker_pb.RegistrationResponse) {
|
||||
|
||||
glog.V(1).Infof("[session %s] Incoming message handler started", sessionID)
|
||||
defer glog.V(1).Infof("[session %s] Incoming message handler stopping", sessionID)
|
||||
streamFailed chan<- struct{},
|
||||
regWait chan<- *worker_pb.RegistrationResponse) {
|
||||
glog.V(1).Infof("INCOMING HANDLER STARTED: Worker %s incoming message handler started", workerID)
|
||||
msgCh := make(chan *worker_pb.AdminMessage)
|
||||
errCh := make(chan error, 1) // Buffered to prevent blocking if the manager is busy
|
||||
// regWait is buffered with size 1 so that the registration response can be sent
|
||||
@@ -504,10 +455,12 @@ func handleIncoming(
|
||||
}()
|
||||
|
||||
for {
|
||||
glog.V(4).Infof("LISTENING: Worker %s waiting for message from admin server", workerID)
|
||||
|
||||
select {
|
||||
case msg := <-msgCh:
|
||||
// Message successfully received from the stream
|
||||
glog.V(4).Infof("[session %s] Received message from admin server: %T", sessionID, msg.Message)
|
||||
glog.V(4).Infof("MESSAGE RECEIVED: Worker %s received message from admin server: %T", workerID, msg.Message)
|
||||
|
||||
// If this is a registration response, also publish to the registration waiter.
|
||||
// regWait is buffered (size 1) so that the response can be sent even if sendRegistration
|
||||
@@ -515,26 +468,26 @@ func handleIncoming(
|
||||
if rr := msg.GetRegistrationResponse(); rr != nil {
|
||||
select {
|
||||
case regWait <- rr:
|
||||
glog.V(3).Infof("[session %s] Registration response routed to waiter", sessionID)
|
||||
glog.V(3).Infof("REGISTRATION RESPONSE: Worker %s routed registration response to waiter", workerID)
|
||||
default:
|
||||
glog.V(2).Infof("[session %s] Registration response dropped (no waiter)", sessionID)
|
||||
glog.V(2).Infof("REGISTRATION RESPONSE DROPPED: Worker %s registration response dropped (no waiter)", workerID)
|
||||
}
|
||||
}
|
||||
|
||||
// Route message to general handler.
|
||||
select {
|
||||
case incoming <- msg:
|
||||
glog.V(3).Infof("[session %s] Message routed to incoming channel", sessionID)
|
||||
glog.V(3).Infof("MESSAGE ROUTED: Worker %s successfully routed message to handler", workerID)
|
||||
case <-time.After(time.Second):
|
||||
glog.Warningf("[session %s] Incoming message buffer full, dropping message: %T", sessionID, msg.Message)
|
||||
glog.Warningf("MESSAGE DROPPED: Worker %s incoming message buffer full, dropping message: %T", workerID, msg.Message)
|
||||
}
|
||||
|
||||
case err := <-errCh:
|
||||
// Stream Receiver goroutine reported an error (EOF or network error)
|
||||
if err == io.EOF {
|
||||
glog.Infof("[session %s] Admin server closed the stream", sessionID)
|
||||
glog.Infof("STREAM CLOSED: Worker %s admin server closed the stream", workerID)
|
||||
} else {
|
||||
glog.Warningf("[session %s] Stream receive error: %v", sessionID, err)
|
||||
glog.Errorf("RECEIVE ERROR: Worker %s failed to receive message from admin: %v", workerID, err)
|
||||
}
|
||||
|
||||
// Signal that stream has failed (non-blocking)
|
||||
@@ -549,23 +502,23 @@ func handleIncoming(
|
||||
select {
|
||||
case cmds <- grpcCommand{action: ActionStreamError, data: err}:
|
||||
default:
|
||||
glog.V(2).Infof("[session %s] Manager busy, queuing stream error asynchronously from incoming handler: %v", sessionID, err)
|
||||
glog.V(2).Infof("Manager busy, queuing stream error asynchronously: %v", err)
|
||||
go func(e error) {
|
||||
select {
|
||||
case cmds <- grpcCommand{action: ActionStreamError, data: e}:
|
||||
case <-time.After(2 * time.Second):
|
||||
glog.Warningf("[session %s] Failed to send stream error to manager from incoming handler, channel blocked: %v", sessionID, e)
|
||||
glog.Warningf("Failed to send stream error to manager, channel blocked: %v", e)
|
||||
}
|
||||
}(err)
|
||||
}
|
||||
|
||||
// Exit the main handler loop
|
||||
glog.V(1).Infof("[session %s] Incoming message handler stopping due to stream error", sessionID)
|
||||
glog.V(1).Infof("INCOMING HANDLER STOPPED: Worker %s stopping incoming handler due to stream error", workerID)
|
||||
return
|
||||
|
||||
case <-streamExit:
|
||||
// Manager closed this channel, signaling a controlled disconnection.
|
||||
glog.V(1).Infof("[session %s] Incoming message handler stopping - received exit signal", sessionID)
|
||||
glog.V(1).Infof("INCOMING HANDLER STOPPED: Worker %s stopping incoming handler - received exit signal", workerID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,7 +195,7 @@ func NewWorker(config *types.WorkerConfig) (*Worker, error) {
|
||||
|
||||
func (w *Worker) managerLoop() {
|
||||
w.state = &workerState{
|
||||
running: false,
|
||||
startTime: time.Now(),
|
||||
stopChan: make(chan struct{}),
|
||||
currentTasks: make(map[string]*types.TaskInput),
|
||||
}
|
||||
@@ -428,7 +428,6 @@ func (w *Worker) Start() error {
|
||||
|
||||
// Start starts the worker
|
||||
func (w *Worker) handleStart(cmd workerCommand) {
|
||||
glog.Infof("Worker %s handleStart called", w.id)
|
||||
if w.state.running {
|
||||
cmd.resp <- fmt.Errorf("worker is already running")
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user