mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
429aef6833 | ||
|
|
f2d2b6f492 | ||
|
|
3181e9185b | ||
|
|
89f7618519 | ||
|
|
11231b4ac6 | ||
|
|
0bd5eec418 | ||
|
|
0744b654ca | ||
|
|
b56f7ee321 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.49"
|
||||
appVersion: "4.48"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.49.0
|
||||
version: 4.48.2
|
||||
+1099
-1094
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 55 KiB |
@@ -153,9 +153,6 @@ func (h *FileBrowserHandlers) uploadFileGrpc(ctx context.Context, filePath strin
|
||||
ChunkSize: adminUploadChunkSize,
|
||||
MimeType: mimeType,
|
||||
AssignFunc: assignFunc,
|
||||
LookupJwtFunc: func(lookupCtx context.Context, fileId string) security.EncodedJwt {
|
||||
return operation.LookupJwt(lookupCtx, h.adminServer.GetMasterClient().GetMaster(lookupCtx), h.adminServer.GetGrpcDialOption(), fileId)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
// Partial chunks come back even on error so we can clean them up rather
|
||||
|
||||
@@ -238,7 +238,7 @@ func writeFiles(idChan chan int, fileIdLineChan chan string, s *stat) {
|
||||
}
|
||||
var jwtAuthorization security.EncodedJwt
|
||||
if isSecure {
|
||||
jwtAuthorization = operation.LookupJwt(context.Background(), b.masterClient.GetMaster(context.Background()), b.grpcDialOption, df.fp.Fid)
|
||||
jwtAuthorization = operation.LookupJwt(b.masterClient.GetMaster(context.Background()), b.grpcDialOption, df.fp.Fid)
|
||||
}
|
||||
if e := util_http.Delete(fmt.Sprintf("http://%s/%s", df.fp.Server, df.fp.Fid), string(jwtAuthorization)); e == nil {
|
||||
s.completed++
|
||||
|
||||
@@ -140,63 +140,20 @@ func (option *RemoteSyncOptions) makeEventProcessor(remoteStorage *remote_pb.Rem
|
||||
if filer_pb.IsEmpty(resp) {
|
||||
return nil
|
||||
}
|
||||
mustSend := false
|
||||
if message.OldEntry != nil && message.NewEntry != nil {
|
||||
reshaped, inMount := reshapeCrossMountRename(mountedDir, resp)
|
||||
if !inMount {
|
||||
return nil
|
||||
}
|
||||
// a create reshaped from a rename into the mount can carry a
|
||||
// RemoteEntry earned at the old path: it stamps the old key, so
|
||||
// it cannot vouch for this destination
|
||||
mustSend = filer_pb.IsCreate(reshaped)
|
||||
resp, message = reshaped, reshaped.EventNotification
|
||||
}
|
||||
if filer_pb.IsCreate(resp) {
|
||||
if isMultipartUploadFile(message.NewParentPath, message.NewEntry.Name) {
|
||||
return nil
|
||||
}
|
||||
if isSystemPath(message.NewParentPath, message.NewEntry.Name) {
|
||||
glog.V(2).Infof("skipping create of system path: %s/%s", message.NewParentPath, message.NewEntry.Name)
|
||||
return nil
|
||||
}
|
||||
// Propagate delete markers as deletions on the remote.
|
||||
// Delete markers are zero-content version entries, so they
|
||||
// would be filtered out by the HasData check below.
|
||||
if isDeleteMarker(message.NewEntry) {
|
||||
if newParent, newName, ok := rewriteVersionedSourcePath(message.NewParentPath, message.NewEntry.Name); ok {
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(newParent, newName), remoteStorageMountLocation)
|
||||
return syncDeleteMarker(client, option, message, dest)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !filer.HasData(message.NewEntry) {
|
||||
return nil
|
||||
}
|
||||
glog.V(2).Infof("create: %+v", resp)
|
||||
if !shouldSendToRemote(message.NewEntry) {
|
||||
glog.V(2).Infof("skipping creating: %+v", resp)
|
||||
return nil
|
||||
}
|
||||
// Rewrite internal versioning paths to the original S3 key
|
||||
// to prevent double-versioning when central also has versioning enabled
|
||||
parentPath, entryName := message.NewParentPath, message.NewEntry.Name
|
||||
isRewrittenVersion := false
|
||||
if newParent, newName, ok := rewriteVersionedSourcePath(parentPath, entryName); ok {
|
||||
glog.V(0).Infof("rewrite versioned path %s/%s -> %s/%s", parentPath, entryName, newParent, newName)
|
||||
parentPath, entryName = newParent, newName
|
||||
isRewrittenVersion = true
|
||||
}
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(parentPath, entryName), remoteStorageMountLocation)
|
||||
if message.NewEntry.IsDirectory {
|
||||
glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
|
||||
return client.WriteDirectory(dest, remoteWriteEntry(message.NewEntry, *option.storageClass))
|
||||
}
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, remoteWriteEntry(message.NewEntry, *option.storageClass), dest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
|
||||
return nil
|
||||
}
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
// Skip updateLocalEntry for versioned rewrites: the logical
|
||||
// object (e.g. file.xml) has no filer entry in versioned
|
||||
// buckets, and stamping the internal v_* entry with a
|
||||
// RemoteEntry for the logical key is semantically wrong.
|
||||
// Replay is safe because S3 PutObject is idempotent.
|
||||
if isRewrittenVersion {
|
||||
return nil
|
||||
}
|
||||
return updateLocalEntry(option, message.NewParentPath, message.NewEntry, remoteEntry)
|
||||
return processCreateEvent(option, filerSource, *option.storageClass, client, mountedDir, remoteStorageMountLocation, resp, mustSend)
|
||||
}
|
||||
if filer_pb.IsDelete(resp) {
|
||||
return processDeleteEvent(filerSource, client, mountedDir, remoteStorageMountLocation, resp)
|
||||
@@ -210,6 +167,131 @@ func (option *RemoteSyncOptions) makeEventProcessor(remoteStorage *remote_pb.Rem
|
||||
return eachEntryFunc, nil
|
||||
}
|
||||
|
||||
// reshapeCrossMountRename maps an update event onto the side of it the mount
|
||||
// covers. The subscription delivers a rename when either of its paths lies
|
||||
// under the mounted directory, and only a path under it maps to a remote
|
||||
// key: toRemoteStorageLocation slices the mount prefix off, which panics on
|
||||
// a shorter path and names a key in the wrong tree on a longer one. A rename
|
||||
// into the mount is the creation of the new entry, a rename out of it the
|
||||
// deletion of the old entry's object, unless that entry is remote-only and
|
||||
// the object holds its only copy. An update with both paths inside is
|
||||
// returned as is; one with neither is not the mount's (false).
|
||||
func reshapeCrossMountRename(mountedDir string, resp *filer_pb.SubscribeMetadataResponse) (*filer_pb.SubscribeMetadataResponse, bool) {
|
||||
message := resp.EventNotification
|
||||
oldInMount := isUnderMount(mountedDir, resp.Directory, message.OldEntry.Name)
|
||||
newInMount := isUnderMount(mountedDir, message.NewParentPath, message.NewEntry.Name)
|
||||
switch {
|
||||
case oldInMount && newInMount:
|
||||
return resp, true
|
||||
case newInMount:
|
||||
glog.V(0).Infof("rename into mount %s: %s/%s -> %s/%s, creating", mountedDir, resp.Directory, message.OldEntry.Name, message.NewParentPath, message.NewEntry.Name)
|
||||
return &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: message.NewParentPath,
|
||||
EventNotification: &filer_pb.EventNotification{NewEntry: message.NewEntry, NewParentPath: message.NewParentPath, Signatures: message.Signatures},
|
||||
TsNs: resp.TsNs,
|
||||
}, true
|
||||
case oldInMount:
|
||||
if isRemoteOnly(message.OldEntry) {
|
||||
glog.V(0).Infof("rename out of mount %s: %s/%s -> %s/%s, keeping the remote-only object", mountedDir, resp.Directory, message.OldEntry.Name, message.NewParentPath, message.NewEntry.Name)
|
||||
return nil, false
|
||||
}
|
||||
glog.V(0).Infof("rename out of mount %s: %s/%s -> %s/%s, deleting", mountedDir, resp.Directory, message.OldEntry.Name, message.NewParentPath, message.NewEntry.Name)
|
||||
return &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: resp.Directory,
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: message.OldEntry, Signatures: message.Signatures},
|
||||
TsNs: resp.TsNs,
|
||||
}, true
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// isUnderMount reports whether dir/name is the mounted directory or lies
|
||||
// below it; a trailing slash on the mount flag does not change the answer.
|
||||
func isUnderMount(mountedDir string, dir string, name string) bool {
|
||||
mount := strings.TrimSuffix(mountedDir, "/")
|
||||
path := string(util.NewFullPath(dir, name))
|
||||
return path == mount || strings.HasPrefix(path, mount+"/")
|
||||
}
|
||||
|
||||
// processCreateEvent uploads a created entry to the remote key its path maps
|
||||
// to. mustSend skips the sync-stamp check: a create reshaped out of a rename
|
||||
// into the mount inherits a RemoteEntry stamped at the old path's key, which
|
||||
// says nothing about whether this destination holds the content.
|
||||
func processCreateEvent(
|
||||
filerClient filer_pb.FilerClient,
|
||||
filerSource filer_pb.FilerClient,
|
||||
storageClass string,
|
||||
client remote_storage.RemoteStorageClient,
|
||||
mountedDir string,
|
||||
remoteStorageMountLocation *remote_pb.RemoteStorageLocation,
|
||||
resp *filer_pb.SubscribeMetadataResponse,
|
||||
mustSend bool,
|
||||
) error {
|
||||
message := resp.EventNotification
|
||||
if isMultipartUploadFile(message.NewParentPath, message.NewEntry.Name) {
|
||||
return nil
|
||||
}
|
||||
if isSystemPath(message.NewParentPath, message.NewEntry.Name) {
|
||||
glog.V(2).Infof("skipping create of system path: %s/%s", message.NewParentPath, message.NewEntry.Name)
|
||||
return nil
|
||||
}
|
||||
// Propagate delete markers as deletions on the remote.
|
||||
// Delete markers are zero-content version entries, so they
|
||||
// would be filtered out by the HasData check below.
|
||||
if isDeleteMarker(message.NewEntry) {
|
||||
if newParent, newName, ok := rewriteVersionedSourcePath(message.NewParentPath, message.NewEntry.Name); ok {
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(newParent, newName), remoteStorageMountLocation)
|
||||
return syncDeleteMarker(client, filerClient, message, dest)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// A create reshaped from a rename into the mount (mustSend) writes an empty
|
||||
// entry as a zero-byte object; a dropped local copy still skips since the
|
||||
// rename already copied its object to the new key. A stamped entry whose
|
||||
// size diverged since (a truncate) is not a dropped copy and sends its
|
||||
// new content.
|
||||
if !filer.HasData(message.NewEntry) && !(mustSend && !isDroppedLocalCopy(message.NewEntry)) {
|
||||
return nil
|
||||
}
|
||||
glog.V(2).Infof("create: %+v", resp)
|
||||
if !mustSend && !shouldSendToRemote(message.NewEntry) {
|
||||
glog.V(2).Infof("skipping creating: %+v", resp)
|
||||
return nil
|
||||
}
|
||||
// Rewrite internal versioning paths to the original S3 key
|
||||
// to prevent double-versioning when central also has versioning enabled
|
||||
parentPath, entryName := message.NewParentPath, message.NewEntry.Name
|
||||
isRewrittenVersion := false
|
||||
if newParent, newName, ok := rewriteVersionedSourcePath(parentPath, entryName); ok {
|
||||
glog.V(0).Infof("rewrite versioned path %s/%s -> %s/%s", parentPath, entryName, newParent, newName)
|
||||
parentPath, entryName = newParent, newName
|
||||
isRewrittenVersion = true
|
||||
}
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(parentPath, entryName), remoteStorageMountLocation)
|
||||
if message.NewEntry.IsDirectory {
|
||||
glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
|
||||
return client.WriteDirectory(dest, remoteWriteEntry(message.NewEntry, storageClass))
|
||||
}
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, remoteWriteEntry(message.NewEntry, storageClass), dest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
|
||||
return nil
|
||||
}
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
// Skip updateLocalEntry for versioned rewrites: the logical
|
||||
// object (e.g. file.xml) has no filer entry in versioned
|
||||
// buckets, and stamping the internal v_* entry with a
|
||||
// RemoteEntry for the logical key is semantically wrong.
|
||||
// Replay is safe because S3 PutObject is idempotent.
|
||||
if isRewrittenVersion {
|
||||
return nil
|
||||
}
|
||||
return updateLocalEntry(filerClient, message.NewParentPath, message.NewEntry, remoteEntry)
|
||||
}
|
||||
|
||||
// processDeleteEvent removes the remote object an entry mapped to. A remote
|
||||
// object that is already absent counts as deleted: the entry was never
|
||||
// uploaded (created and deleted faster than the sync ran, or a replay of an
|
||||
|
||||
@@ -2017,6 +2017,238 @@ func TestMetadataUpdateKeepsTheStoredStampOnNilResult(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestReshapeCrossMountRename covers an update event with a path outside
|
||||
// the mount. The subscription delivers a rename when either path is under
|
||||
// the mount, and an update of the /etc/remote directory entry itself through
|
||||
// the daemon's /etc/remote prefix; processUpdateEvent then sliced the mount
|
||||
// prefix off both paths, which panics on a path shorter than the mount (seen
|
||||
// on a replay: "slice bounds out of range [20:11]" on the 11-byte
|
||||
// /etc/remote, every restart dying on the same event) and names a key in the
|
||||
// wrong tree on a longer one.
|
||||
func TestReshapeCrossMountRename(t *testing.T) {
|
||||
const mount = "/buckets/mount"
|
||||
chunked := func(name string) *filer_pb.Entry {
|
||||
return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669, FileSize: 7}, Chunks: []*filer_pb.FileChunk{{FileId: "3,01", Size: 7}}}
|
||||
}
|
||||
event := func(oldDir, oldName, newDir, newName string, oldEntry *filer_pb.Entry) *filer_pb.SubscribeMetadataResponse {
|
||||
if oldEntry == nil {
|
||||
oldEntry = chunked(oldName)
|
||||
}
|
||||
return &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: oldDir,
|
||||
TsNs: 42,
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: oldEntry, NewParentPath: newDir, NewEntry: chunked(newName), Signatures: []int32{7}},
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("into the mount from a shorter path is a create of the new entry", func(t *testing.T) {
|
||||
resp := event("/plain", "in.txt", mount+"/lock", "in.txt", nil)
|
||||
got, inMount := reshapeCrossMountRename(mount, resp)
|
||||
if !inMount || !filer_pb.IsCreate(got) {
|
||||
t.Fatalf("got %+v inMount=%v, want a create", got, inMount)
|
||||
}
|
||||
if got.Directory != mount+"/lock" || got.EventNotification.NewParentPath != mount+"/lock" || got.EventNotification.NewEntry.Name != "in.txt" {
|
||||
t.Errorf("create at %s/%s (dir %s), want %s/in.txt", got.EventNotification.NewParentPath, got.EventNotification.NewEntry.Name, got.Directory, mount+"/lock")
|
||||
}
|
||||
if got.TsNs != 42 || len(got.EventNotification.Signatures) != 1 {
|
||||
t.Errorf("timestamp and signatures must carry over: %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("into the mount from a longer path outside it is a create, not a key in the wrong tree", func(t *testing.T) {
|
||||
resp := event("/buckets/other/deeper/tree", "x.txt", mount, "x.txt", nil)
|
||||
got, inMount := reshapeCrossMountRename(mount, resp)
|
||||
if !inMount || !filer_pb.IsCreate(got) || got.EventNotification.NewParentPath != mount {
|
||||
t.Fatalf("got %+v inMount=%v, want a create under %s", got, inMount, mount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("out of the mount is a delete of the old entry", func(t *testing.T) {
|
||||
resp := event(mount+"/lock", "out.txt", "/plain", "out.txt", nil)
|
||||
got, inMount := reshapeCrossMountRename(mount, resp)
|
||||
if !inMount || !filer_pb.IsDelete(got) {
|
||||
t.Fatalf("got %+v inMount=%v, want a delete", got, inMount)
|
||||
}
|
||||
if got.Directory != mount+"/lock" || got.EventNotification.OldEntry.Name != "out.txt" {
|
||||
t.Errorf("delete of %s/%s, want %s/out.txt", got.Directory, got.EventNotification.OldEntry.Name, mount+"/lock")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("out of the mount keeps the object of a remote-only entry", func(t *testing.T) {
|
||||
remoteOnly := &filer_pb.Entry{Name: "out.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669, FileSize: 7}, RemoteEntry: &filer_pb.RemoteEntry{StorageName: "b2", RemoteSize: 7, RemoteMtime: 1786096669}}
|
||||
resp := event(mount+"/lock", "out.txt", "/plain", "out.txt", remoteOnly)
|
||||
if got, inMount := reshapeCrossMountRename(mount, resp); inMount || got != nil {
|
||||
t.Fatalf("got %+v inMount=%v, want the event dropped", got, inMount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("both paths inside is the update itself", func(t *testing.T) {
|
||||
resp := event(mount+"/a", "x.txt", mount+"/b", "y.txt", nil)
|
||||
if got, inMount := reshapeCrossMountRename(mount, resp); !inMount || got != resp {
|
||||
t.Fatalf("got %+v inMount=%v, want the same event", got, inMount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an update of the /etc/remote directory entry itself is not the mount's event", func(t *testing.T) {
|
||||
dirEntry := &filer_pb.Entry{Name: "remote", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}}
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/etc",
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: dirEntry, NewParentPath: "/etc", NewEntry: dirEntry},
|
||||
}
|
||||
if got, inMount := reshapeCrossMountRename("/buckets/c4x-storage", resp); inMount || got != nil {
|
||||
t.Fatalf("got %+v inMount=%v, want the event dropped", got, inMount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("neither path inside is not the mount's event", func(t *testing.T) {
|
||||
resp := event("/plain", "x.txt", "/buckets/mounted-not", "x.txt", nil)
|
||||
if got, inMount := reshapeCrossMountRename(mount, resp); inMount || got != nil {
|
||||
t.Fatalf("got %+v inMount=%v, want the event dropped", got, inMount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a trailing slash on the mount flag changes nothing", func(t *testing.T) {
|
||||
resp := event("/plain", "in.txt", mount, "in.txt", nil)
|
||||
if got, inMount := reshapeCrossMountRename(mount+"/", resp); !inMount || !filer_pb.IsCreate(got) {
|
||||
t.Fatalf("got %+v inMount=%v, want a create", got, inMount)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestRenameIntoMountUploadsDespiteTheOldStamp covers a file synced at a path
|
||||
// under the mount, renamed out (which deleted its remote object), and renamed
|
||||
// back in: the entry still carries the RemoteEntry the first sync stamped, so
|
||||
// shouldSendToRemote would skip the create the reshape made, leaving the new
|
||||
// key without an object. A reshaped create must send unconditionally.
|
||||
func TestRenameIntoMountUploadsDespiteTheOldStamp(t *testing.T) {
|
||||
const mountedDir = "/buckets/mount"
|
||||
mountLoc := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/"}
|
||||
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "b2", RemoteETag: "abc", RemoteSize: 7, RemoteMtime: 1786096669, LastLocalSyncTsNs: 1786096669*1e9 + 1}
|
||||
newEntry := &filer_pb.Entry{
|
||||
Name: "back.txt",
|
||||
Content: []byte("payload"),
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669},
|
||||
RemoteEntry: stamp,
|
||||
}
|
||||
resp, inMount := reshapeCrossMountRename(mountedDir, &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/plain",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: "back.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}, RemoteEntry: stamp},
|
||||
NewParentPath: mountedDir + "/lock",
|
||||
NewEntry: newEntry,
|
||||
},
|
||||
})
|
||||
if !inMount || !filer_pb.IsCreate(resp) {
|
||||
t.Fatalf("reshape = %+v inMount=%v, want a create", resp, inMount)
|
||||
}
|
||||
if shouldSendToRemote(resp.EventNotification.NewEntry) {
|
||||
t.Fatal("precondition: the stamp the rename carried should fail shouldSendToRemote")
|
||||
}
|
||||
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: newEntry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantWrite := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/lock/back.txt"}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], wantWrite) {
|
||||
t.Fatalf("writes = %+v, want the new key %s written", remote.writes, remote_storage.FormatLocation(wantWrite))
|
||||
}
|
||||
|
||||
// a plain create keeps trusting the stamp
|
||||
remote = &recordingRemote{}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want the stamped create skipped", remote.writes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRenameIntoMountWritesAnEmptyFile: a rename into the mount is reshaped
|
||||
// to a create with mustSend, and an empty entry has no data for the HasData
|
||||
// gate; the new key still takes a zero-byte object. A remote-only entry holds
|
||||
// nothing local to send and is skipped as before.
|
||||
func TestRenameIntoMountWritesAnEmptyFile(t *testing.T) {
|
||||
const mountedDir = "/buckets/mount"
|
||||
mountLoc := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/"}
|
||||
renameIn := func(entry *filer_pb.Entry) *filer_pb.SubscribeMetadataResponse {
|
||||
resp, inMount := reshapeCrossMountRename(mountedDir, &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/plain",
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: entry, NewParentPath: mountedDir + "/lock", NewEntry: entry},
|
||||
})
|
||||
if !inMount || !filer_pb.IsCreate(resp) {
|
||||
t.Fatalf("reshape = %+v inMount=%v, want a create", resp, inMount)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
wantWrite := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/lock/empty.txt"}
|
||||
|
||||
t.Run("an empty entry writes a zero-byte object", func(t *testing.T) {
|
||||
entry := &filer_pb.Entry{Name: "empty.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}}
|
||||
if filer.HasData(entry) {
|
||||
t.Fatal("precondition: an empty entry carries no data")
|
||||
}
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: entry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn(entry), true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], wantWrite) {
|
||||
t.Errorf("writes = %+v, want the new key %s written", remote.writes, remote_storage.FormatLocation(wantWrite))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a remote-only entry still skips", func(t *testing.T) {
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "b2", RemoteETag: "abc", RemoteSize: 7, RemoteMtime: 1786096669, LastLocalSyncTsNs: 1786096669*1e9 + 1}
|
||||
entry := &filer_pb.Entry{Name: "empty.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669, FileSize: 7}, RemoteEntry: stamp}
|
||||
if !isRemoteOnly(entry) {
|
||||
t.Fatal("precondition: the entry should be remote-only")
|
||||
}
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: entry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn(entry), true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none for a remote-only entry", remote.writes)
|
||||
}
|
||||
})
|
||||
|
||||
// a stamped entry truncated to zero is not remote-only content: its stamp
|
||||
// describes bytes the file no longer holds, so the new key takes a
|
||||
// zero-byte object
|
||||
t.Run("a truncated stamped entry writes a zero-byte object", func(t *testing.T) {
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "b2", RemoteETag: "abc", RemoteSize: 7, RemoteMtime: 1786096669, LastLocalSyncTsNs: 1786096669*1e9 + 1}
|
||||
entry := &filer_pb.Entry{Name: "empty.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}, RemoteEntry: stamp}
|
||||
if !isRemoteOnly(entry) || isDroppedLocalCopy(entry) {
|
||||
t.Fatal("precondition: a truncated stamped entry reports remote-only but is not a dropped copy")
|
||||
}
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: entry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn(entry), true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], wantWrite) {
|
||||
t.Errorf("writes = %+v, want the new key %s written", remote.writes, remote_storage.FormatLocation(wantWrite))
|
||||
}
|
||||
})
|
||||
|
||||
// an ordinary create of an empty entry is unchanged: no object
|
||||
t.Run("a plain empty create still writes nothing", func(t *testing.T) {
|
||||
entry := &filer_pb.Entry{Name: "empty.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}}
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: entry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn(entry), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want the empty create skipped", remote.writes)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestIsSystemPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
dir string
|
||||
@@ -2086,4 +2318,3 @@ func TestRemoteSyncSkipsSystemFolder(t *testing.T) {
|
||||
t.Fatalf("expected 0 remote deletes for system path, got %d deletes", len(remote.deletes))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,13 +53,7 @@ type IAMManager struct {
|
||||
oidcRetryAgain bool
|
||||
// oidcRefreshMu serializes refreshes from reading the store to handing
|
||||
// STS the result, so an older snapshot cannot replace a newer one.
|
||||
oidcRefreshMu sync.Mutex
|
||||
// oidcManagedProviders caches providers refreshOIDCProvidersFrom built,
|
||||
// keyed by record identity, so an unchanged record reuses its provider:
|
||||
// rebuilding would drop the provider's consumed-token (jti) replay cache
|
||||
// and let an already-used token be presented again. Guarded by
|
||||
// oidcRefreshMu.
|
||||
oidcManagedProviders map[string]*oidcManagedProvider
|
||||
oidcRefreshMu sync.Mutex
|
||||
oidcAuditSink OIDCProviderAuditSink
|
||||
revocationStore SessionRevocationStore
|
||||
filerAddressProvider func() string // Function to get current filer address
|
||||
@@ -949,65 +943,14 @@ func (m *IAMManager) refreshOIDCProvidersFrom(ctx context.Context, store OIDCPro
|
||||
return fmt.Errorf("list OIDC providers: the store was replaced during the refresh")
|
||||
}
|
||||
byIssuer := make(map[string][]sts.ScopedOIDCProvider, len(records))
|
||||
if m.oidcManagedProviders == nil {
|
||||
m.oidcManagedProviders = make(map[string]*oidcManagedProvider)
|
||||
}
|
||||
seen := make(map[string]struct{}, len(records))
|
||||
// Records for one issuer with identical validation settings share a single
|
||||
// provider — and with it the consumed-token (jti) replay store — so a token
|
||||
// spent through one account's record stays spent through the other's too.
|
||||
sharedProviders := make(map[string]*oidc.OIDCProvider)
|
||||
for _, rec := range records {
|
||||
if rec == nil || rec.URL == "" {
|
||||
continue
|
||||
}
|
||||
key := rec.ARN
|
||||
if key == "" {
|
||||
key = rec.URL + "\x00" + rec.AccountID
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
fingerprint := oidcProviderFingerprint(rec)
|
||||
configFingerprint := oidcProviderConfigFingerprint(rec)
|
||||
var provider *oidc.OIDCProvider
|
||||
cached := m.oidcManagedProviders[key]
|
||||
if shared, ok := sharedProviders[configFingerprint]; ok {
|
||||
provider = shared
|
||||
if cached != nil && cached.provider != nil && cached.provider != shared {
|
||||
// The record's own provider is superseded; its consumed
|
||||
// tokens move to the shared store so none reopen for replay.
|
||||
shared.MergeReplayStateFrom(cached.provider)
|
||||
}
|
||||
m.oidcManagedProviders[key] = &oidcManagedProvider{fingerprint: fingerprint, provider: provider}
|
||||
if cached != nil && cached.provider != nil && cached.provider != shared && !m.oidcProviderStillReferenced(cached.provider) {
|
||||
if err := cached.provider.Shutdown(ctx); err != nil {
|
||||
glog.Warningf("shutdown superseded OIDC provider %s: %v", rec.ARN, err)
|
||||
}
|
||||
}
|
||||
} else if cached != nil && cached.fingerprint == fingerprint {
|
||||
provider = cached.provider
|
||||
sharedProviders[configFingerprint] = provider
|
||||
} else {
|
||||
var err error
|
||||
provider, err = buildOIDCProviderFromRecord(rec)
|
||||
if err != nil {
|
||||
delete(m.oidcManagedProviders, key)
|
||||
glog.Warningf("skip refreshing OIDC provider %s: %v", rec.ARN, err)
|
||||
continue
|
||||
}
|
||||
if cached != nil && cached.provider != nil {
|
||||
// The rebuild must keep rejecting tokens the replaced
|
||||
// provider consumed; carry its replay store over, then stop
|
||||
// its cleanup worker so only the new one sweeps the store —
|
||||
// unless another record still references that provider.
|
||||
provider.AdoptReplayStateFrom(cached.provider)
|
||||
}
|
||||
sharedProviders[configFingerprint] = provider
|
||||
m.oidcManagedProviders[key] = &oidcManagedProvider{fingerprint: fingerprint, provider: provider}
|
||||
if cached != nil && cached.provider != nil && !m.oidcProviderStillReferenced(cached.provider) {
|
||||
if err := cached.provider.Shutdown(ctx); err != nil {
|
||||
glog.Warningf("shutdown replaced OIDC provider %s: %v", rec.ARN, err)
|
||||
}
|
||||
}
|
||||
provider, err := buildOIDCProviderFromRecord(rec)
|
||||
if err != nil {
|
||||
glog.Warningf("skip refreshing OIDC provider %s: %v", rec.ARN, err)
|
||||
continue
|
||||
}
|
||||
// Multiple records may share an issuer when each is scoped to a
|
||||
// different account; STS picks the right one at validation time
|
||||
@@ -1017,71 +960,10 @@ func (m *IAMManager) refreshOIDCProvidersFrom(ctx context.Context, store OIDCPro
|
||||
Provider: provider,
|
||||
})
|
||||
}
|
||||
for key, managed := range m.oidcManagedProviders {
|
||||
if _, ok := seen[key]; !ok {
|
||||
delete(m.oidcManagedProviders, key)
|
||||
// A removed record's provider may be shared by records that are
|
||||
// still present; shut it down only when nothing references it.
|
||||
if managed.provider != nil && !m.oidcProviderStillReferenced(managed.provider) {
|
||||
if err := managed.provider.Shutdown(ctx); err != nil {
|
||||
glog.Warningf("shutdown removed OIDC provider %s: %v", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
m.stsService.SetIAMManagedOIDCProviders(byIssuer)
|
||||
return nil
|
||||
}
|
||||
|
||||
// oidcManagedProvider is a runtime provider together with the fingerprint of
|
||||
// the record it was built from.
|
||||
type oidcManagedProvider struct {
|
||||
fingerprint string
|
||||
provider *oidc.OIDCProvider
|
||||
}
|
||||
|
||||
// oidcProviderStillReferenced reports whether any managed record still points
|
||||
// at the provider, so a shared provider is not shut down with a removed record.
|
||||
func (m *IAMManager) oidcProviderStillReferenced(provider *oidc.OIDCProvider) bool {
|
||||
for _, managed := range m.oidcManagedProviders {
|
||||
if managed.provider == provider {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// oidcProviderFingerprint identifies the record content a provider was built
|
||||
// from, so a refresh rebuilds the provider only when that content changed.
|
||||
func oidcProviderFingerprint(rec *OIDCProviderRecord) string {
|
||||
key, _ := json.Marshal(struct {
|
||||
ARN string
|
||||
AccountID string
|
||||
URL string
|
||||
ClientIDs []string
|
||||
Thumbprints []string
|
||||
AllowedPrincipalTagKeys []string
|
||||
PolicyClaim string
|
||||
}{rec.ARN, rec.AccountID, rec.URL, rec.ClientIDs, rec.Thumbprints, rec.AllowedPrincipalTagKeys, rec.PolicyClaim})
|
||||
sum := sha256.Sum256(key)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// oidcProviderConfigFingerprint identifies the validation settings a provider
|
||||
// is built from — everything buildOIDCProviderFromRecord consumes except the
|
||||
// record's name — so records that differ only in identity reuse one provider.
|
||||
func oidcProviderConfigFingerprint(rec *OIDCProviderRecord) string {
|
||||
key, _ := json.Marshal(&oidc.OIDCConfig{
|
||||
Issuer: rec.URL,
|
||||
ClientIDs: rec.ClientIDs,
|
||||
Thumbprints: rec.Thumbprints,
|
||||
AllowedPrincipalTagKeys: rec.AllowedPrincipalTagKeys,
|
||||
PolicyClaim: rec.PolicyClaim,
|
||||
})
|
||||
sum := sha256.Sum256(key)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// buildOIDCProviderFromRecord turns a stored record into a runtime
|
||||
// OIDCProvider. The provider name is the ARN so re-registration is
|
||||
// idempotent and never collides with static-config entries.
|
||||
|
||||
@@ -559,93 +559,3 @@ func TestAFailureDuringARetryIsNotDropped(t *testing.T) {
|
||||
}
|
||||
assert.GreaterOrEqual(t, store.successes(), 2, "the retry ended on its first success, dropping the refresh that failed while it ran")
|
||||
}
|
||||
|
||||
// A refresh must not rebuild a provider whose record is unchanged: rebuilding
|
||||
// would drop the provider's consumed-token (jti) replay cache and let an
|
||||
// already-used token be presented again.
|
||||
func TestRefreshReusesProviderWhileRecordIsUnchanged(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewMemoryOIDCProviderStore()
|
||||
mgr := startServer(t, store)
|
||||
|
||||
arn := arnOf(t, persistTestAPIIssuer)
|
||||
require.NoError(t, store.StoreProvider(ctx, "", &OIDCProviderRecord{
|
||||
ARN: arn, URL: persistTestAPIIssuer, ClientIDs: []string{"aud"},
|
||||
}))
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
first := mgr.oidcManagedProviders[arn].provider
|
||||
require.NotNil(t, first)
|
||||
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
assert.Same(t, first, mgr.oidcManagedProviders[arn].provider,
|
||||
"an unchanged record was rebuilt, dropping its replay cache")
|
||||
|
||||
// A changed record must rebuild so the new configuration applies.
|
||||
require.NoError(t, store.StoreProvider(ctx, "", &OIDCProviderRecord{
|
||||
ARN: arn, URL: persistTestAPIIssuer, ClientIDs: []string{"aud", "aud2"},
|
||||
}))
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
rebuilt := mgr.oidcManagedProviders[arn].provider
|
||||
require.NotNil(t, rebuilt)
|
||||
assert.NotSame(t, first, rebuilt, "a changed record kept the old provider")
|
||||
|
||||
// Deleting the record drops the provider from the cache and the STS map.
|
||||
require.NoError(t, store.DeleteProvider(ctx, "", arn))
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
assert.NotContains(t, mgr.oidcManagedProviders, arn)
|
||||
assert.False(t, stsKnowsIssuer(t, mgr, persistTestAPIIssuer))
|
||||
}
|
||||
|
||||
// stsKnowsIssuerForAccount is stsKnowsIssuer through the account-scoped
|
||||
// lookup used for providers that have no global record.
|
||||
func stsKnowsIssuerForAccount(t *testing.T, mgr *IAMManager, issuer, accountID string) bool {
|
||||
t.Helper()
|
||||
tok, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"iss": issuer, "sub": "probe", "aud": "aud", "exp": time.Now().Add(time.Hour).Unix(),
|
||||
}).SignedString([]byte("not-the-providers-key"))
|
||||
require.NoError(t, err)
|
||||
_, _, err = mgr.GetSTSService().ValidateWebIdentityTokenForAccount(context.Background(), tok, accountID)
|
||||
require.Error(t, err, "an unsigned-by-provider token for %s was accepted", issuer)
|
||||
return !strings.Contains(err.Error(), "no identity provider registered")
|
||||
}
|
||||
|
||||
// Two records for one issuer with identical validation settings share a
|
||||
// single provider — and with it the consumed-token (jti) replay store — so a
|
||||
// token spent through one account's record stays spent through the other's.
|
||||
// Removing one record of the pair must not shut the shared provider down.
|
||||
func TestSameIssuerRecordsShareOneProvider(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewMemoryOIDCProviderStore()
|
||||
mgr := startServer(t, store)
|
||||
|
||||
arnA := arnOf(t, persistTestAPIIssuer) + "-account-a"
|
||||
arnB := arnOf(t, persistTestAPIIssuer) + "-account-b"
|
||||
for _, rec := range []*OIDCProviderRecord{
|
||||
{ARN: arnA, URL: persistTestAPIIssuer, AccountID: "111111111111", ClientIDs: []string{"aud"}},
|
||||
{ARN: arnB, URL: persistTestAPIIssuer, AccountID: "222222222222", ClientIDs: []string{"aud"}},
|
||||
} {
|
||||
require.NoError(t, store.StoreProvider(ctx, "", rec))
|
||||
}
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
|
||||
shared := mgr.oidcManagedProviders[arnA].provider
|
||||
require.NotNil(t, shared)
|
||||
assert.Same(t, shared, mgr.oidcManagedProviders[arnB].provider,
|
||||
"identical records for one issuer built separate replay stores")
|
||||
|
||||
// Removing one record of the pair keeps the shared provider alive.
|
||||
require.NoError(t, store.DeleteProvider(ctx, "", arnA))
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
assert.Same(t, shared, mgr.oidcManagedProviders[arnB].provider,
|
||||
"a removed sibling record shut down the shared provider")
|
||||
assert.True(t, stsKnowsIssuerForAccount(t, mgr, persistTestAPIIssuer, "222222222222"))
|
||||
|
||||
// The remaining record diverging rebuilds its own provider.
|
||||
require.NoError(t, store.StoreProvider(ctx, "", &OIDCProviderRecord{
|
||||
ARN: arnB, URL: persistTestAPIIssuer, AccountID: "222222222222", ClientIDs: []string{"b-aud"},
|
||||
}))
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
assert.NotSame(t, shared, mgr.oidcManagedProviders[arnB].provider,
|
||||
"a changed record kept the shared provider")
|
||||
assert.True(t, stsKnowsIssuerForAccount(t, mgr, persistTestAPIIssuer, "222222222222"))
|
||||
}
|
||||
@@ -75,17 +75,6 @@ func (m *MockOIDCProvider) Authenticate(ctx context.Context, token string) (*pro
|
||||
return identity, nil
|
||||
}
|
||||
|
||||
// AuthenticateSingleUse stays on the mock path: the embedded provider's
|
||||
// method would bypass the mock's test data and demand a real JWKS.
|
||||
func (m *MockOIDCProvider) AuthenticateSingleUse(ctx context.Context, token string) (*providers.ExternalIdentity, error) {
|
||||
return m.Authenticate(ctx, token)
|
||||
}
|
||||
|
||||
// ValidateTokenSingleUse stays on the mock path; see AuthenticateSingleUse.
|
||||
func (m *MockOIDCProvider) ValidateTokenSingleUse(ctx context.Context, token string) (*providers.TokenClaims, error) {
|
||||
return m.ValidateToken(ctx, token)
|
||||
}
|
||||
|
||||
// ValidateToken validates tokens using test data
|
||||
func (m *MockOIDCProvider) ValidateToken(ctx context.Context, token string) (*providers.TokenClaims, error) {
|
||||
if !m.initialized {
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"crypto/elliptic"
|
||||
"crypto/rsa"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
@@ -20,7 +19,6 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
@@ -29,44 +27,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
)
|
||||
|
||||
const (
|
||||
// clockSkewTolerance matches the typical JWT library clock skew allowance (RFC 7519)
|
||||
clockSkewTolerance = 5 * time.Minute
|
||||
// defaultJTICacheSize is the default maximum number of JTI entries to cache
|
||||
defaultJTICacheSize = 10000
|
||||
// defaultCleanupInterval is how often to scan for expired JTI entries
|
||||
defaultCleanupInterval = 5 * time.Minute
|
||||
// eagerCleanupMinInterval rate limits opportunistic sweeps near capacity
|
||||
eagerCleanupMinInterval = 5 * time.Second
|
||||
// tokenFingerprintPrefix marks replay-cache keys derived from the token's
|
||||
// own fingerprint, used when the token carries no usable jti claim
|
||||
tokenFingerprintPrefix = "fp:"
|
||||
)
|
||||
|
||||
// jtiEntry represents a cached JTI with metadata
|
||||
type jtiEntry struct {
|
||||
subject string
|
||||
expiresAt time.Time
|
||||
// uncounted marks an entry merged in past the capacity bound: it keeps
|
||||
// rejecting replays but does not charge jtiCount, so merged excess can
|
||||
// neither reject new exchanges nor be double-counted when swept.
|
||||
uncounted bool
|
||||
}
|
||||
|
||||
// OIDCProvider implements OpenID Connect authentication with JTI replay protection.
|
||||
//
|
||||
// Replay Protection:
|
||||
// The provider validates the 'jti' (JWT ID) claim to prevent token replay attacks.
|
||||
// Each JTI is stored in memory until the token expires. If a token with a duplicate
|
||||
// JTI is presented, it is rejected with ErrProviderTokenReplayed.
|
||||
//
|
||||
// The JTI cache is bounded by JTICacheMaxSize and uses automatic TTL-based expiration.
|
||||
// A token without a usable jti claim is tracked by the token's own fingerprint
|
||||
// instead, so a repeated presentation is still detected as a replay.
|
||||
//
|
||||
// Thread Safety:
|
||||
// All methods are safe for concurrent use. The JTI cache uses atomic LoadOrStore
|
||||
// operations to prevent TOCTOU race conditions.
|
||||
// OIDCProvider implements OpenID Connect authentication
|
||||
type OIDCProvider struct {
|
||||
name string
|
||||
config *OIDCConfig
|
||||
@@ -83,32 +44,6 @@ type OIDCProvider struct {
|
||||
jwksFetchedAt time.Time
|
||||
resolvedJWKSUri string
|
||||
discoveryFailed bool
|
||||
|
||||
// JTI replay protection fields. jtiStore and jtiCount are allocated once
|
||||
// in NewOIDCProvider and survive re-initialization, so a config refresh
|
||||
// cannot reopen already-consumed tokens for replay.
|
||||
jtiEnabled atomic.Bool
|
||||
jtiStore *sync.Map // map[string]*jtiEntry - atomic storage for consumed token keys
|
||||
jtiCount *atomic.Int64 // entries in jtiStore; shared with the store
|
||||
jtiMaxSize atomic.Int64
|
||||
jtiLastSweep atomic.Int64 // unix nano of the last sweep; rate limits eager cleanups
|
||||
|
||||
// jtiStoreMu guards the jtiStore/jtiCount pair: replay-state handoffs
|
||||
// (AdoptReplayStateFrom, MergeReplayStateFrom) repoint them under the
|
||||
// write lock while the consume path holds a read lock, so a consume can
|
||||
// never land in a store the handoff already drained and abandoned.
|
||||
// It is always acquired before jtiSweepMu, never while holding it.
|
||||
jtiStoreMu sync.RWMutex
|
||||
|
||||
// jtiMu guards the lifecycle of the cleanup worker: jtiCleanupCancel and
|
||||
// jtiCleanupDone. The worker itself only touches jtiStore/jtiCount, so
|
||||
// holding jtiMu while waiting for it is safe.
|
||||
jtiMu sync.Mutex
|
||||
jtiCleanupCancel context.CancelFunc
|
||||
jtiCleanupDone chan struct{} // Closed when cleanup goroutine exits
|
||||
|
||||
// jtiSweepMu serializes cache sweeps so at most one scan runs at a time.
|
||||
jtiSweepMu sync.Mutex
|
||||
}
|
||||
|
||||
// OIDCConfig holds OIDC provider configuration
|
||||
@@ -172,13 +107,6 @@ type OIDCConfig struct {
|
||||
// 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"`
|
||||
|
||||
// JTIReplayProtectionEnabled enables token replay protection via JTI tracking (default: true)
|
||||
// Use pointer to distinguish between "not set" (nil = default true) and "explicitly false"
|
||||
JTIReplayProtectionEnabled *bool `json:"jtiReplayProtectionEnabled,omitempty"`
|
||||
|
||||
// JTICacheMaxSize sets maximum number of JTI entries to cache (default: 10000)
|
||||
JTICacheMaxSize int `json:"jtiCacheMaxSize,omitempty"`
|
||||
}
|
||||
|
||||
// PrincipalTagsClaim is the AWS-defined namespace claim that carries
|
||||
@@ -391,8 +319,6 @@ func NewOIDCProvider(name string) *OIDCProvider {
|
||||
return &OIDCProvider{
|
||||
name: name,
|
||||
httpClient: &http.Client{Timeout: 30 * time.Second, CheckRedirect: refuseDowngradeRedirect},
|
||||
jtiStore: &sync.Map{},
|
||||
jtiCount: &atomic.Int64{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -503,62 +429,10 @@ func (p *OIDCProvider) Initialize(config interface{}) error {
|
||||
CheckRedirect: refuseDowngradeRedirect,
|
||||
}
|
||||
|
||||
// Configure JTI replay protection last, so a config failure above cannot
|
||||
// leave a running worker behind. A previous worker is always stopped,
|
||||
// whether the new configuration enables protection or disables it.
|
||||
// The consumed-token store survives re-initialization: resetting it would
|
||||
// let already-seen tokens be replayed against the refreshed provider.
|
||||
jtiEnabled := true
|
||||
if oidcConfig.JTIReplayProtectionEnabled != nil {
|
||||
jtiEnabled = *oidcConfig.JTIReplayProtectionEnabled
|
||||
}
|
||||
|
||||
p.jtiMu.Lock()
|
||||
p.stopJTICleanupWorkerLocked()
|
||||
if jtiEnabled {
|
||||
maxSize := int64(oidcConfig.JTICacheMaxSize)
|
||||
if maxSize <= 0 {
|
||||
maxSize = defaultJTICacheSize
|
||||
}
|
||||
// the bound must land before the flag: a consume that sees enabled
|
||||
// with a zero bound would reject the first token it registers
|
||||
p.jtiMaxSize.Store(maxSize)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
p.jtiCleanupCancel = cancel
|
||||
p.jtiCleanupDone = done
|
||||
p.jtiEnabled.Store(true)
|
||||
p.jtiMu.Unlock()
|
||||
|
||||
go p.cleanupExpiredJTIs(ctx, done, defaultCleanupInterval)
|
||||
glog.V(2).Infof("OIDC provider %q: JTI replay protection enabled (max size: %d)", p.name, maxSize)
|
||||
} else {
|
||||
p.jtiEnabled.Store(false)
|
||||
p.jtiMu.Unlock()
|
||||
glog.Warningf("OIDC provider %q: JTI replay protection is DISABLED", p.name)
|
||||
}
|
||||
|
||||
// For testing, we'll skip the actual OIDC client initialization
|
||||
return nil
|
||||
}
|
||||
|
||||
// stopJTICleanupWorkerLocked cancels the current cleanup goroutine and waits
|
||||
// briefly for it to exit. Caller must hold jtiMu.
|
||||
func (p *OIDCProvider) stopJTICleanupWorkerLocked() {
|
||||
if p.jtiCleanupCancel == nil {
|
||||
return
|
||||
}
|
||||
p.jtiCleanupCancel()
|
||||
select {
|
||||
case <-p.jtiCleanupDone:
|
||||
glog.V(3).Infof("OIDC provider %q: JTI cleanup goroutine exited", p.name)
|
||||
case <-time.After(2 * time.Second):
|
||||
glog.Warningf("OIDC provider %q: Timeout waiting for JTI cleanup goroutine", p.name)
|
||||
}
|
||||
p.jtiCleanupCancel = nil
|
||||
p.jtiCleanupDone = nil
|
||||
}
|
||||
|
||||
// validateConfig validates the OIDC configuration
|
||||
func (p *OIDCProvider) validateConfig(config *OIDCConfig) error {
|
||||
if config.Issuer == "" {
|
||||
@@ -605,18 +479,6 @@ func (p *OIDCProvider) allowedAudiences() []string {
|
||||
|
||||
// Authenticate authenticates a user with an OIDC token
|
||||
func (p *OIDCProvider) Authenticate(ctx context.Context, token string) (*providers.ExternalIdentity, error) {
|
||||
return p.authenticate(ctx, token, false)
|
||||
}
|
||||
|
||||
// AuthenticateSingleUse authenticates and consumes the token so a second
|
||||
// presentation is rejected as a replay. The web-identity exchange uses it,
|
||||
// where a token buys a session exactly once; callers that validate the same
|
||||
// token on every request use Authenticate.
|
||||
func (p *OIDCProvider) AuthenticateSingleUse(ctx context.Context, token string) (*providers.ExternalIdentity, error) {
|
||||
return p.authenticate(ctx, token, true)
|
||||
}
|
||||
|
||||
func (p *OIDCProvider) authenticate(ctx context.Context, token string, singleUse bool) (*providers.ExternalIdentity, error) {
|
||||
if !p.initialized {
|
||||
return nil, fmt.Errorf("provider not initialized")
|
||||
}
|
||||
@@ -626,7 +488,7 @@ func (p *OIDCProvider) authenticate(ctx context.Context, token string, singleUse
|
||||
}
|
||||
|
||||
// Validate token and get claims
|
||||
claims, err := p.validateToken(ctx, token, singleUse)
|
||||
claims, err := p.ValidateToken(ctx, token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -793,16 +655,6 @@ func (p *OIDCProvider) getUserInfoWithToken(ctx context.Context, userID, accessT
|
||||
|
||||
// ValidateToken validates an OIDC JWT token
|
||||
func (p *OIDCProvider) ValidateToken(ctx context.Context, token string) (*providers.TokenClaims, error) {
|
||||
return p.validateToken(ctx, token, false)
|
||||
}
|
||||
|
||||
// ValidateTokenSingleUse validates and consumes the token: a second
|
||||
// presentation of it is rejected as a replay. See AuthenticateSingleUse.
|
||||
func (p *OIDCProvider) ValidateTokenSingleUse(ctx context.Context, token string) (*providers.TokenClaims, error) {
|
||||
return p.validateToken(ctx, token, true)
|
||||
}
|
||||
|
||||
func (p *OIDCProvider) validateToken(ctx context.Context, token string, singleUse bool) (*providers.TokenClaims, error) {
|
||||
if !p.initialized {
|
||||
return nil, fmt.Errorf("provider not initialized")
|
||||
}
|
||||
@@ -935,87 +787,6 @@ func (p *OIDCProvider) validateToken(ctx context.Context, token string, singleUs
|
||||
tokenClaims.Claims[key] = value
|
||||
}
|
||||
|
||||
// Extract and validate JTI claim for replay protection. The check runs
|
||||
// only for single-use callers: a bearer token is meant to be presented on
|
||||
// every request, so validating it must not consume it.
|
||||
if singleUse && p.jtiEnabled.Load() {
|
||||
jti, _ := claims["jti"].(string)
|
||||
key := jti
|
||||
if key == "" {
|
||||
// Providers that issue no jti cannot be tracked by claim, so the
|
||||
// signed input keys the entry: a repeated presentation of the same
|
||||
// claims is a replay even when the signature bytes differ (e.g.
|
||||
// ECDSA s/N-s malleability).
|
||||
signingInput := token
|
||||
if i := strings.LastIndexByte(token, '.'); i > 0 {
|
||||
signingInput = token[:i]
|
||||
}
|
||||
sum := sha256.Sum256([]byte(signingInput))
|
||||
key = tokenFingerprintPrefix + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
expiresAt := tokenClaims.ExpiresAt
|
||||
if expiresAt.IsZero() {
|
||||
// a cache slot is freed only by expiry, so a token without exp
|
||||
// would hold it forever and eventually exhaust the bound
|
||||
return nil, fmt.Errorf("%w: missing exp claim", providers.ErrProviderMissingClaims)
|
||||
}
|
||||
expiresAt = expiresAt.Add(clockSkewTolerance)
|
||||
if !time.Now().Before(expiresAt) {
|
||||
return nil, fmt.Errorf("%w: token expired", providers.ErrProviderTokenExpired)
|
||||
}
|
||||
|
||||
entry := &jtiEntry{
|
||||
subject: subject,
|
||||
expiresAt: expiresAt,
|
||||
}
|
||||
|
||||
// The read lock pins the store/count pair for the whole test-and-set
|
||||
// so a replay-state handoff cannot repoint them mid-check and strand
|
||||
// this consume in an abandoned store.
|
||||
p.jtiStoreMu.RLock()
|
||||
store, count := p.jtiStore, p.jtiCount
|
||||
|
||||
// Atomic test-and-set detects replays before any capacity work runs,
|
||||
// so a replayed token cannot trigger cleanup scans.
|
||||
if _, loaded := store.LoadOrStore(key, entry); loaded {
|
||||
p.jtiStoreMu.RUnlock()
|
||||
glog.Warningf("OIDC provider %q: Token replay detected (jti: %s)",
|
||||
p.name, jtiLogKey(key))
|
||||
return nil, fmt.Errorf("%w: jti %s has already been used",
|
||||
providers.ErrProviderTokenReplayed, jtiLogKey(key))
|
||||
}
|
||||
|
||||
// The count is incremented as part of the insert, so concurrent
|
||||
// validations cannot all slip under the limit: whoever pushes the
|
||||
// count over evicts their own entry and is rejected.
|
||||
newCount := count.Add(1)
|
||||
maxSize := p.jtiMaxSize.Load()
|
||||
if newCount > maxSize {
|
||||
// Over the bound: expired entries may still occupy slots, so
|
||||
// reclaim them with a synchronized sweep before rejecting.
|
||||
p.sweepJTIStore(store, count)
|
||||
if count.Load() > maxSize {
|
||||
if _, loaded := store.LoadAndDelete(key); loaded {
|
||||
count.Add(-1)
|
||||
}
|
||||
p.jtiStoreMu.RUnlock()
|
||||
glog.Errorf("OIDC provider %q: JTI cache FULL (%d entries) - rejecting token. "+
|
||||
"This may indicate a DoS attack or insufficient cache size. Consider increasing JTICacheMaxSize.",
|
||||
p.name, maxSize)
|
||||
return nil, fmt.Errorf("JTI cache capacity exceeded")
|
||||
}
|
||||
} else if newCount >= maxSize*9/10 {
|
||||
glog.Warningf("OIDC provider %q: JTI cache at %d%% capacity (%d/%d), triggering eager cleanup",
|
||||
p.name, (newCount*100)/maxSize, newCount, maxSize)
|
||||
go p.performEagerCleanup()
|
||||
}
|
||||
p.jtiStoreMu.RUnlock()
|
||||
|
||||
glog.V(4).Infof("OIDC provider %q: Registered JTI %s (expires at %v, cache size: %d)",
|
||||
p.name, jtiLogKey(key), expiresAt, newCount)
|
||||
}
|
||||
|
||||
return tokenClaims, nil
|
||||
}
|
||||
|
||||
@@ -1444,195 +1215,3 @@ func (p *OIDCProvider) mapUserInfoToIdentity(userInfo map[string]interface{}) *p
|
||||
|
||||
return identity
|
||||
}
|
||||
|
||||
// evictExpiredJTIs removes entries whose expiry has passed and returns how
|
||||
// many it deleted. Caller must hold jtiSweepMu.
|
||||
func (p *OIDCProvider) evictExpiredJTIs(now time.Time, store *sync.Map, count *atomic.Int64) int {
|
||||
removed := 0
|
||||
store.Range(func(key, value interface{}) bool {
|
||||
expiresAt := value.(*jtiEntry).expiresAt
|
||||
if !expiresAt.IsZero() && now.After(expiresAt) {
|
||||
// LoadAndDelete reports whether this call actually removed the
|
||||
// entry, so concurrent deletes cannot decrement the count twice.
|
||||
if v, loaded := store.LoadAndDelete(key); loaded {
|
||||
if !v.(*jtiEntry).uncounted {
|
||||
count.Add(-1)
|
||||
}
|
||||
removed++
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return removed
|
||||
}
|
||||
|
||||
// replayState returns the provider's current store/count pair.
|
||||
func (p *OIDCProvider) replayState() (*sync.Map, *atomic.Int64) {
|
||||
p.jtiStoreMu.RLock()
|
||||
defer p.jtiStoreMu.RUnlock()
|
||||
return p.jtiStore, p.jtiCount
|
||||
}
|
||||
|
||||
// sweepJTIStore runs one serialized expiry scan over the given store. It only
|
||||
// takes jtiSweepMu, so callers already holding jtiStoreMu may use it.
|
||||
func (p *OIDCProvider) sweepJTIStore(store *sync.Map, count *atomic.Int64) {
|
||||
p.jtiSweepMu.Lock()
|
||||
defer p.jtiSweepMu.Unlock()
|
||||
p.jtiLastSweep.Store(time.Now().UnixNano())
|
||||
if removed := p.evictExpiredJTIs(time.Now(), store, count); removed > 0 {
|
||||
glog.V(4).Infof("OIDC provider %q: Cleaned up %d expired JTI entries (remaining: %d)",
|
||||
p.name, removed, count.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// sweepExpiredJTIs runs a scan that is guaranteed to complete before the
|
||||
// caller proceeds; the capacity-rejection path uses it so a fresh token is
|
||||
// not refused while expired entries still hold slots.
|
||||
func (p *OIDCProvider) sweepExpiredJTIs() {
|
||||
store, count := p.replayState()
|
||||
p.sweepJTIStore(store, count)
|
||||
}
|
||||
|
||||
// performEagerCleanup performs an opportunistic cleanup of expired JTI
|
||||
// entries when the cache approaches capacity. At most one sweep runs at a
|
||||
// time and no more often than eagerCleanupMinInterval, so a burst of
|
||||
// requests near the limit cannot each turn into a full-cache scan.
|
||||
func (p *OIDCProvider) performEagerCleanup() {
|
||||
if !p.jtiEnabled.Load() {
|
||||
return
|
||||
}
|
||||
if time.Since(time.Unix(0, p.jtiLastSweep.Load())) < eagerCleanupMinInterval {
|
||||
return
|
||||
}
|
||||
store, count := p.replayState()
|
||||
if !p.jtiSweepMu.TryLock() {
|
||||
return
|
||||
}
|
||||
defer p.jtiSweepMu.Unlock()
|
||||
p.jtiLastSweep.Store(time.Now().UnixNano())
|
||||
|
||||
beforeCount := count.Load()
|
||||
if removed := p.evictExpiredJTIs(time.Now(), store, count); removed > 0 {
|
||||
glog.Infof("OIDC provider %q: Eager cleanup removed %d expired JTI entries (%d -> %d)",
|
||||
p.name, removed, beforeCount, count.Load())
|
||||
} else {
|
||||
glog.Warningf("OIDC provider %q: Eager cleanup found no expired entries to remove. "+
|
||||
"Cache may be filled with valid long-lived tokens. Consider increasing JTICacheMaxSize.",
|
||||
p.name)
|
||||
}
|
||||
}
|
||||
|
||||
// cleanupExpiredJTIs periodically removes expired JTI entries from the cache.
|
||||
// This prevents memory growth by removing JTIs after their tokens have expired.
|
||||
// Runs in a background goroutine until ctx is cancelled; done is closed on exit.
|
||||
func (p *OIDCProvider) cleanupExpiredJTIs(ctx context.Context, done chan struct{}, interval time.Duration) {
|
||||
defer close(done)
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
glog.V(3).Infof("OIDC provider %q: JTI cleanup goroutine started (interval: %v)", p.name, interval)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
glog.V(3).Infof("OIDC provider %q: JTI cleanup goroutine stopping", p.name)
|
||||
return
|
||||
case <-ticker.C:
|
||||
p.sweepExpiredJTIs()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown gracefully stops the JTI cleanup goroutine.
|
||||
// Should be called when the provider is being shut down to prevent goroutine leaks.
|
||||
func (p *OIDCProvider) Shutdown(ctx context.Context) error {
|
||||
p.jtiMu.Lock()
|
||||
cancel, done := p.jtiCleanupCancel, p.jtiCleanupDone
|
||||
p.jtiMu.Unlock()
|
||||
|
||||
if cancel == nil {
|
||||
return nil
|
||||
}
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
glog.V(2).Infof("OIDC provider %q: Cleanup goroutine shutdown complete", p.name)
|
||||
case <-ctx.Done():
|
||||
glog.Warningf("OIDC provider %q: Shutdown timeout waiting for cleanup goroutine: %v", p.name, ctx.Err())
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
p.jtiMu.Lock()
|
||||
if p.jtiCleanupDone == done {
|
||||
p.jtiCleanupCancel = nil
|
||||
p.jtiCleanupDone = nil
|
||||
}
|
||||
p.jtiMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// AdoptReplayStateFrom takes over the consumed-token store of the provider it
|
||||
// replaces, so tokens it already saw stay rejected across the rebuild. The
|
||||
// caller must shut down the replaced provider; only one cleanup worker may
|
||||
// sweep the shared store at a time. Call before the new provider serves
|
||||
// validators; jtiSweepMu excludes its own cleanup worker during the swap.
|
||||
func (p *OIDCProvider) AdoptReplayStateFrom(old *OIDCProvider) {
|
||||
if old == nil || old == p {
|
||||
return
|
||||
}
|
||||
p.jtiStoreMu.Lock()
|
||||
p.jtiSweepMu.Lock()
|
||||
p.jtiStore, p.jtiCount = old.jtiStore, old.jtiCount
|
||||
p.jtiSweepMu.Unlock()
|
||||
p.jtiStoreMu.Unlock()
|
||||
}
|
||||
|
||||
// MergeReplayStateFrom hands this provider's store to another provider and
|
||||
// then folds the other's consumed-token entries in, so rejections the other
|
||||
// recorded keep holding when its records move to a shared provider. Repointing
|
||||
// first means tokens the other still consumes — in-flight exchanges or ones
|
||||
// routed to it before the provider map updates — land in the shared store
|
||||
// instead of a store this merge already drained. Unlike AdoptReplayStateFrom
|
||||
// it swaps nothing of its own, so it is safe on a provider that is already
|
||||
// serving validators.
|
||||
func (p *OIDCProvider) MergeReplayStateFrom(other *OIDCProvider) {
|
||||
if other == nil || other == p {
|
||||
return
|
||||
}
|
||||
p.jtiStoreMu.RLock()
|
||||
defer p.jtiStoreMu.RUnlock()
|
||||
store, count := p.jtiStore, p.jtiCount
|
||||
|
||||
other.jtiStoreMu.Lock()
|
||||
oldStore := other.jtiStore
|
||||
if oldStore == store {
|
||||
other.jtiStoreMu.Unlock()
|
||||
return
|
||||
}
|
||||
other.jtiStore, other.jtiCount = store, count
|
||||
other.jtiStoreMu.Unlock()
|
||||
|
||||
p.jtiSweepMu.Lock()
|
||||
defer p.jtiSweepMu.Unlock()
|
||||
now := time.Now()
|
||||
oldStore.Range(func(key, value interface{}) bool {
|
||||
entry := value.(*jtiEntry)
|
||||
if expiresAt := entry.expiresAt; !expiresAt.IsZero() && now.After(expiresAt) {
|
||||
return true
|
||||
}
|
||||
// A consumed token is never dropped to fit the bound: merged entries
|
||||
// stay but do not charge the count, so a store filled past the bound
|
||||
// by the merge cannot reject new exchanges while it drains by expiry.
|
||||
store.LoadOrStore(key, &jtiEntry{subject: entry.subject, expiresAt: entry.expiresAt, uncounted: true})
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// jtiLogKey redacts a token identifier for logs and error strings: a stable
|
||||
// fingerprint that still lets operators correlate repeated presentations.
|
||||
func jtiLogKey(jti string) string {
|
||||
sum := sha256.Sum256([]byte(jti))
|
||||
return hex.EncodeToString(sum[:8])
|
||||
}
|
||||
+12
-1080
File diff suppressed because it is too large.
Load diff
@@ -19,7 +19,4 @@ var (
|
||||
|
||||
// ErrProviderMissingClaims indicates that required claims are missing from the token
|
||||
ErrProviderMissingClaims = errors.New("provider: missing required claims")
|
||||
|
||||
// ErrProviderTokenReplayed is returned when a token with duplicate JTI is detected
|
||||
ErrProviderTokenReplayed = errors.New("provider: token has been replayed")
|
||||
)
|
||||
+15
-17
@@ -42,23 +42,21 @@ const (
|
||||
|
||||
// Configuration Field Names
|
||||
const (
|
||||
ConfigFieldFilerAddress = "filerAddress"
|
||||
ConfigFieldBasePath = "basePath"
|
||||
ConfigFieldIssuer = "issuer"
|
||||
ConfigFieldClientID = "clientId"
|
||||
ConfigFieldClientIDs = "clientIds"
|
||||
ConfigFieldThumbprints = "thumbprints"
|
||||
ConfigFieldAllowedPrincipalTagKeys = "allowedPrincipalTagKeys"
|
||||
ConfigFieldPolicyClaim = "policyClaim"
|
||||
ConfigFieldClientSecret = "clientSecret"
|
||||
ConfigFieldJWKSUri = "jwksUri"
|
||||
ConfigFieldScopes = "scopes"
|
||||
ConfigFieldUserInfoUri = "userInfoUri"
|
||||
ConfigFieldRedirectUri = "redirectUri"
|
||||
ConfigFieldTLSCACert = "tlsCaCert"
|
||||
ConfigFieldTLSInsecureSkipVerify = "tlsInsecureSkipVerify"
|
||||
ConfigFieldJTIReplayProtectionEnabled = "jtiReplayProtectionEnabled"
|
||||
ConfigFieldJTICacheMaxSize = "jtiCacheMaxSize"
|
||||
ConfigFieldFilerAddress = "filerAddress"
|
||||
ConfigFieldBasePath = "basePath"
|
||||
ConfigFieldIssuer = "issuer"
|
||||
ConfigFieldClientID = "clientId"
|
||||
ConfigFieldClientIDs = "clientIds"
|
||||
ConfigFieldThumbprints = "thumbprints"
|
||||
ConfigFieldAllowedPrincipalTagKeys = "allowedPrincipalTagKeys"
|
||||
ConfigFieldPolicyClaim = "policyClaim"
|
||||
ConfigFieldClientSecret = "clientSecret"
|
||||
ConfigFieldJWKSUri = "jwksUri"
|
||||
ConfigFieldScopes = "scopes"
|
||||
ConfigFieldUserInfoUri = "userInfoUri"
|
||||
ConfigFieldRedirectUri = "redirectUri"
|
||||
ConfigFieldTLSCACert = "tlsCaCert"
|
||||
ConfigFieldTLSInsecureSkipVerify = "tlsInsecureSkipVerify"
|
||||
)
|
||||
|
||||
// Error Messages
|
||||
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
// lookupOIDCProviderForAccount; the lookup never calls Authenticate.
|
||||
type stubIdentityProvider struct{ name string }
|
||||
|
||||
func (s *stubIdentityProvider) Name() string { return s.name }
|
||||
func (s *stubIdentityProvider) Initialize(interface{}) error { return nil }
|
||||
func (s *stubIdentityProvider) Name() string { return s.name }
|
||||
func (s *stubIdentityProvider) Initialize(interface{}) error { return nil }
|
||||
func (s *stubIdentityProvider) Authenticate(context.Context, string) (*providers.ExternalIdentity, error) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -103,51 +103,3 @@ func TestLookupOIDCProviderForAccountFallsBackToStatic(t *testing.T) {
|
||||
t.Fatalf("expected static-config provider as last resort, got %v ok=%v", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// shutdownTrackingProvider records Shutdown calls so tests can observe which
|
||||
// replaced providers the swap released.
|
||||
type shutdownTrackingProvider struct {
|
||||
stubIdentityProvider
|
||||
shutdownCalls int32
|
||||
}
|
||||
|
||||
func (s *shutdownTrackingProvider) Shutdown(context.Context) error {
|
||||
s.shutdownCalls++
|
||||
return nil
|
||||
}
|
||||
|
||||
// A provider dropped from the managed map owns a background JTI cleanup
|
||||
// worker; replacing the map must shut it down, while providers that stay in
|
||||
// the map keep running.
|
||||
func TestSetIAMManagedOIDCProvidersShutsDownDroppedProviders(t *testing.T) {
|
||||
dropped := &shutdownTrackingProvider{stubIdentityProvider{name: "dropped"}, 0}
|
||||
kept := &shutdownTrackingProvider{stubIdentityProvider{name: "kept"}, 0}
|
||||
added := &shutdownTrackingProvider{stubIdentityProvider{name: "added"}, 0}
|
||||
|
||||
s := &STSService{issuerToProvider: map[string]providers.IdentityProvider{}}
|
||||
s.SetIAMManagedOIDCProviders(map[string][]ScopedOIDCProvider{
|
||||
"https://a.example.com": {{Provider: dropped}},
|
||||
"https://b.example.com": {{Provider: kept}, {AccountID: "111111111111", Provider: kept}},
|
||||
})
|
||||
|
||||
s.SetIAMManagedOIDCProviders(map[string][]ScopedOIDCProvider{
|
||||
"https://b.example.com": {{Provider: kept}},
|
||||
"https://c.example.com": {{Provider: added}},
|
||||
})
|
||||
|
||||
if dropped.shutdownCalls != 1 {
|
||||
t.Fatalf("dropped provider was shut down %d times, want 1", dropped.shutdownCalls)
|
||||
}
|
||||
if kept.shutdownCalls != 0 {
|
||||
t.Fatalf("kept provider was shut down %d times, want 0", kept.shutdownCalls)
|
||||
}
|
||||
if added.shutdownCalls != 0 {
|
||||
t.Fatalf("newly added provider was shut down %d times, want 0", added.shutdownCalls)
|
||||
}
|
||||
|
||||
// Clearing the map releases the remaining providers.
|
||||
s.SetIAMManagedOIDCProviders(nil)
|
||||
if kept.shutdownCalls != 1 || added.shutdownCalls != 1 {
|
||||
t.Fatalf("clearing the map shut down kept=%d added=%d, want 1 each", kept.shutdownCalls, added.shutdownCalls)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package sts
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -155,21 +154,6 @@ func (f *ProviderFactory) convertToOIDCConfig(configMap map[string]interface{})
|
||||
config.TLSInsecureSkipVerify = tlsInsecureSkipVerify
|
||||
}
|
||||
|
||||
if enabled, ok := configMap[ConfigFieldJTIReplayProtectionEnabled].(bool); ok {
|
||||
config.JTIReplayProtectionEnabled = &enabled
|
||||
}
|
||||
|
||||
switch maxSize := configMap[ConfigFieldJTICacheMaxSize].(type) {
|
||||
case float64:
|
||||
config.JTICacheMaxSize = int(maxSize)
|
||||
case int:
|
||||
config.JTICacheMaxSize = maxSize
|
||||
case json.Number:
|
||||
if n, err := maxSize.Int64(); err == nil {
|
||||
config.JTICacheMaxSize = int(n)
|
||||
}
|
||||
}
|
||||
|
||||
// Convert claims mapping
|
||||
if claimsMapInterface, ok := configMap["claimsMapping"]; ok {
|
||||
claimsMap, err := f.convertToStringMap(claimsMapInterface)
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
package sts
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConvertToOIDCConfigCarriesJTISettings(t *testing.T) {
|
||||
factory := NewProviderFactory()
|
||||
|
||||
config, err := factory.convertToOIDCConfig(map[string]interface{}{
|
||||
"issuer": "https://issuer.example",
|
||||
"clientId": "client",
|
||||
"jtiReplayProtectionEnabled": false,
|
||||
"jtiCacheMaxSize": float64(42),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, config.JTIReplayProtectionEnabled)
|
||||
assert.False(t, *config.JTIReplayProtectionEnabled)
|
||||
assert.Equal(t, 42, config.JTICacheMaxSize)
|
||||
|
||||
config, err = factory.convertToOIDCConfig(map[string]interface{}{
|
||||
"issuer": "https://issuer.example",
|
||||
"clientId": "client",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, config.JTIReplayProtectionEnabled)
|
||||
assert.Zero(t, config.JTICacheMaxSize)
|
||||
}
|
||||
@@ -512,35 +512,8 @@ func (s *STSService) SetIAMManagedOIDCProviders(byIssuer map[string][]ScopedOIDC
|
||||
}
|
||||
}
|
||||
s.iamManagedOIDCMu.Lock()
|
||||
old := s.iamManagedOIDCByIssuer
|
||||
s.iamManagedOIDCByIssuer = cp
|
||||
s.iamManagedOIDCMu.Unlock()
|
||||
|
||||
// Providers dropped by the swap may own background workers (the JTI
|
||||
// cleanup goroutine); stop them so a replaced provider does not leak.
|
||||
kept := make(map[providers.IdentityProvider]struct{})
|
||||
for _, scoped := range cp {
|
||||
for _, sp := range scoped {
|
||||
kept[sp.Provider] = struct{}{}
|
||||
}
|
||||
}
|
||||
stopped := make(map[providers.IdentityProvider]struct{})
|
||||
for _, scoped := range old {
|
||||
for _, sp := range scoped {
|
||||
if _, ok := kept[sp.Provider]; ok {
|
||||
continue
|
||||
}
|
||||
if _, ok := stopped[sp.Provider]; ok {
|
||||
continue
|
||||
}
|
||||
stopped[sp.Provider] = struct{}{}
|
||||
if sd, ok := sp.Provider.(interface{ Shutdown(context.Context) error }); ok {
|
||||
if err := sd.Shutdown(context.Background()); err != nil {
|
||||
glog.Warningf("OIDC provider %q shutdown after replacement: %v", sp.Provider.Name(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// lookupOIDCProviderForAccount returns the provider that should validate
|
||||
@@ -614,7 +587,7 @@ func (s *STSService) AssumeRoleWithWebIdentity(ctx context.Context, request *Ass
|
||||
// caller passed a legacy or claim-based ARN, in which case lookup falls
|
||||
// back to a global (account-less) record only.
|
||||
roleAccountID := utils.ParseRoleARN(request.RoleArn).AccountID
|
||||
externalIdentity, provider, err := s.validateWebIdentityToken(ctx, request.WebIdentityToken, roleAccountID, true)
|
||||
externalIdentity, provider, err := s.validateWebIdentityToken(ctx, request.WebIdentityToken, roleAccountID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to validate web identity token: %w", err)
|
||||
}
|
||||
@@ -1008,7 +981,7 @@ func (s *STSService) validateAssumeRoleWithWebIdentityRequest(request *AssumeRol
|
||||
// validateWebIdentityToken validates the web identity token with strict issuer-to-provider mapping
|
||||
// SECURITY: JWT tokens with a specific issuer claim MUST only be validated by the provider for that issuer
|
||||
// SECURITY: This method only accepts JWT tokens. Non-JWT authentication must use AssumeRoleWithCredentials with explicit ProviderName.
|
||||
func (s *STSService) validateWebIdentityToken(ctx context.Context, token, roleAccountID string, singleUse bool) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
func (s *STSService) validateWebIdentityToken(ctx context.Context, token, roleAccountID string) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
// Try to extract issuer from JWT token for strict validation
|
||||
issuer, err := s.extractIssuerFromJWT(token)
|
||||
if err != nil {
|
||||
@@ -1031,10 +1004,8 @@ func (s *STSService) validateWebIdentityToken(ctx context.Context, token, roleAc
|
||||
return nil, nil, fmt.Errorf("no identity provider registered for issuer: %s", issuer)
|
||||
}
|
||||
|
||||
// Authenticate with the correct provider for this issuer. Only the STS
|
||||
// exchange authenticates single-use: a bearer token is presented on every
|
||||
// request, so consuming it here would reject all but the first one.
|
||||
identity, err := authenticateOIDCProvider(ctx, provider, token, singleUse)
|
||||
// Authenticate with the correct provider for this issuer
|
||||
identity, err := provider.Authenticate(ctx, token)
|
||||
if err != nil {
|
||||
// Map provider errors to STS errors using errors.Is() for robust error checking
|
||||
// This eliminates fragile string matching and provides reliable error classification
|
||||
@@ -1066,29 +1037,14 @@ func (s *STSService) validateWebIdentityToken(ctx context.Context, token, roleAc
|
||||
// only, then static-config); call ValidateWebIdentityTokenForAccount when the assumed-role account
|
||||
// is known.
|
||||
func (s *STSService) ValidateWebIdentityToken(ctx context.Context, token string) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
return s.validateWebIdentityToken(ctx, token, "", false)
|
||||
return s.validateWebIdentityToken(ctx, token, "")
|
||||
}
|
||||
|
||||
// ValidateWebIdentityTokenForAccount mirrors ValidateWebIdentityToken but
|
||||
// scopes the IAM-managed provider lookup to roleAccountID. Pass "" for
|
||||
// callers that don't yet know the account (e.g. claim-based mode).
|
||||
func (s *STSService) ValidateWebIdentityTokenForAccount(ctx context.Context, token, roleAccountID string) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
return s.validateWebIdentityToken(ctx, token, roleAccountID, false)
|
||||
}
|
||||
|
||||
// authenticateOIDCProvider authenticates the token, consuming it for replay
|
||||
// protection when the caller is the single-use STS exchange and the provider
|
||||
// supports it. Other providers and non-exchange callers authenticate without
|
||||
// consuming.
|
||||
func authenticateOIDCProvider(ctx context.Context, provider providers.IdentityProvider, token string, singleUse bool) (*providers.ExternalIdentity, error) {
|
||||
if singleUse {
|
||||
if su, ok := provider.(interface {
|
||||
AuthenticateSingleUse(context.Context, string) (*providers.ExternalIdentity, error)
|
||||
}); ok {
|
||||
return su.AuthenticateSingleUse(ctx, token)
|
||||
}
|
||||
}
|
||||
return provider.Authenticate(ctx, token)
|
||||
return s.validateWebIdentityToken(ctx, token, roleAccountID)
|
||||
}
|
||||
|
||||
// extractIssuerFromJWT extracts the issuer (iss) claim from a JWT token without verification
|
||||
|
||||
@@ -157,11 +157,11 @@ func Assign(ctx context.Context, masterFn GetMasterFn, grpcDialOption grpc.DialO
|
||||
return ret, lastError
|
||||
}
|
||||
|
||||
func LookupJwt(ctx context.Context, master pb.ServerAddress, grpcDialOption grpc.DialOption, fileId string) (token security.EncodedJwt) {
|
||||
func LookupJwt(master pb.ServerAddress, grpcDialOption grpc.DialOption, fileId string) (token security.EncodedJwt) {
|
||||
|
||||
WithMasterServerClient(ctx, false, master, grpcDialOption, func(masterClient master_pb.SeaweedClient) error {
|
||||
WithMasterServerClient(context.Background(), false, master, grpcDialOption, func(masterClient master_pb.SeaweedClient) error {
|
||||
|
||||
resp, grpcErr := masterClient.LookupVolume(ctx, &master_pb.LookupVolumeRequest{
|
||||
resp, grpcErr := masterClient.LookupVolume(context.Background(), &master_pb.LookupVolumeRequest{
|
||||
VolumeOrFileIds: []string{fileId},
|
||||
})
|
||||
if grpcErr != nil {
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -46,7 +45,6 @@ type ChunkedUploadOption struct {
|
||||
Cipher bool // encrypt data on volume servers
|
||||
AssignFunc func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error)
|
||||
UploadFunc func(ctx context.Context, data []byte, option *UploadOption) (*UploadResult, error) // Optional: for testing
|
||||
LookupJwtFunc func(ctx context.Context, fileId string) security.EncodedJwt // Optional: renews the volume JWT for a cleanup delete
|
||||
}
|
||||
|
||||
var chunkBufferPool = sync.Pool{
|
||||
@@ -215,7 +213,7 @@ uploadLoop:
|
||||
// failed write can still leave a copy behind. No chunk will name
|
||||
// this fid whether we retry or give up here, and an unreferenced
|
||||
// needle is not garbage vacuum can find, so drop it either way.
|
||||
deleteChunkFromHolders(chunkHolders(assignResult), assignResult.Fid, jwt, opt)
|
||||
deleteChunkFromHolders(chunkHolders(assignResult), assignResult.Fid, jwt)
|
||||
if attempt == chunkAssignAttempts || !ShouldReassignUpload(uploadResultErr) || objectFailed() {
|
||||
break
|
||||
}
|
||||
@@ -415,46 +413,19 @@ func uploadChunkToHolders(ctx context.Context, hosts []string, fid string, data
|
||||
if firstErr != nil {
|
||||
// A failed fan-out records no chunk, so roll back the copies that landed
|
||||
// before the cancel rather than leaking them as orphans.
|
||||
deleteChunkFromHolders(succeeded, fid, jwt, opt)
|
||||
deleteChunkFromHolders(succeeded, fid, jwt)
|
||||
return nil, firstErr
|
||||
}
|
||||
return first, nil
|
||||
}
|
||||
|
||||
// cleanupJwtLookupTimeout bounds a cleanup-token renewal, covering the wait
|
||||
// for a master plus the lookup RPC, so a master outage cannot stall the
|
||||
// rollback of a failed fan-out.
|
||||
const cleanupJwtLookupTimeout = 10 * time.Second
|
||||
|
||||
// deleteChunkFromHolders best-effort removes a needle from each holder it landed
|
||||
// on, using type=replicate so the volume drops only its local copy. A failed
|
||||
// delete falls back to vacuum reclaiming the orphan.
|
||||
func deleteChunkFromHolders(hosts []string, fid string, jwt security.EncodedJwt, opt *ChunkedUploadOption) {
|
||||
// An unresponsive holder can stall the upload past the write JWT's expiry,
|
||||
// so renew the token whenever a holder rejects the delete as unauthorized.
|
||||
// Each holder's delete is retried at most once, and a slow holder that
|
||||
// outlives the renewed token can still trigger another renewal.
|
||||
deleteJwt := jwt
|
||||
func deleteChunkFromHolders(hosts []string, fid string, jwt security.EncodedJwt) {
|
||||
for _, host := range hosts {
|
||||
deleteUrl := fmt.Sprintf("http://%s/%s?type=replicate", host, fid)
|
||||
body, status, err := util_http.DeleteProxied(deleteUrl, string(deleteJwt))
|
||||
if status == http.StatusUnauthorized && opt.LookupJwtFunc != nil {
|
||||
lookupCtx, cancel := context.WithTimeout(context.Background(), cleanupJwtLookupTimeout)
|
||||
token := opt.LookupJwtFunc(lookupCtx, fid)
|
||||
cancel()
|
||||
if token != "" {
|
||||
deleteJwt = token
|
||||
body, status, err = util_http.DeleteProxied(deleteUrl, string(deleteJwt))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
if err := util_http.Delete(fmt.Sprintf("http://%s/%s?type=replicate", host, fid), string(jwt)); err != nil {
|
||||
glog.Warningf("replica fan-out cleanup: delete %s from %s: %v", fid, host, err)
|
||||
continue
|
||||
}
|
||||
switch status {
|
||||
case http.StatusNotFound, http.StatusNoContent, http.StatusAccepted, http.StatusOK:
|
||||
default:
|
||||
glog.Warningf("replica fan-out cleanup: delete %s from %s: status %d: %s", fid, host, status, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,11 +26,13 @@ func TestUploadReaderInChunksReturnsPartialResultsOnError(t *testing.T) {
|
||||
testData := bytes.Repeat([]byte("test data for chunk upload failure testing"), 1000) // ~40KB
|
||||
reader := bytes.NewReader(testData)
|
||||
|
||||
var uploadAttempts int32
|
||||
uploadAttempts := 0
|
||||
|
||||
// Create a mock assign function that succeeds for first chunk, then fails
|
||||
assignFunc := func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error) {
|
||||
if atomic.AddInt32(&uploadAttempts, 1) == 1 {
|
||||
uploadAttempts++
|
||||
|
||||
if uploadAttempts == 1 {
|
||||
// First chunk succeeds
|
||||
return nil, &AssignResult{
|
||||
Fid: "test-fid-1,1234",
|
||||
@@ -677,90 +679,3 @@ func TestUploadReaderInChunksAppendsFsyncWhenAssigned(t *testing.T) {
|
||||
t.Errorf("Expected the upload URL to carry ?fsync=true when the assignment says fsync, got %q", gotUploadUrl)
|
||||
}
|
||||
}
|
||||
|
||||
// A holder that stalls past the assignment JWT's expiry answers the rollback
|
||||
// delete with 401; the cleanup renews the token instead of leaking the copy.
|
||||
func TestDeleteChunkFromHoldersRenewsExpiredJwt(t *testing.T) {
|
||||
var staleDeletes, freshDeletes int32
|
||||
holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodDelete {
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
return
|
||||
}
|
||||
switch r.Header.Get("Authorization") {
|
||||
case "Bearer fresh-jwt":
|
||||
atomic.AddInt32(&freshDeletes, 1)
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
default:
|
||||
atomic.AddInt32(&staleDeletes, 1)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
fmt.Fprint(w, `{"error":"wrong jwt"}`)
|
||||
}
|
||||
}))
|
||||
defer holder.Close()
|
||||
|
||||
lookups := 0
|
||||
deleteChunkFromHolders(
|
||||
[]string{strings.TrimPrefix(holder.URL, "http://")},
|
||||
"1,0a0b0c0d",
|
||||
"stale-jwt",
|
||||
&ChunkedUploadOption{
|
||||
LookupJwtFunc: func(ctx context.Context, fileId string) security.EncodedJwt {
|
||||
lookups++
|
||||
return "fresh-jwt"
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
if lookups != 1 {
|
||||
t.Fatalf("expected one jwt renewal, got %d", lookups)
|
||||
}
|
||||
if atomic.LoadInt32(&freshDeletes) != 1 {
|
||||
t.Fatalf("expected the delete retried with the fresh jwt, got %d fresh deletes", freshDeletes)
|
||||
}
|
||||
}
|
||||
|
||||
// A later holder that rejects the renewed token can trigger another renewal:
|
||||
// the one-retry limit is per holder, not per cleanup pass.
|
||||
func TestDeleteChunkFromHoldersRenewsPerHolder(t *testing.T) {
|
||||
var acceptedDeletes int32
|
||||
holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodDelete {
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Authorization") == "Bearer jwt-2" {
|
||||
atomic.AddInt32(&acceptedDeletes, 1)
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
fmt.Fprint(w, `{"error":"wrong jwt"}`)
|
||||
}))
|
||||
defer holder.Close()
|
||||
|
||||
tokens := []security.EncodedJwt{"jwt-1", "jwt-2"}
|
||||
lookups := 0
|
||||
deleteChunkFromHolders(
|
||||
[]string{
|
||||
strings.TrimPrefix(holder.URL, "http://"),
|
||||
strings.TrimPrefix(holder.URL, "http://"),
|
||||
},
|
||||
"1,0a0b0c0d",
|
||||
"stale-jwt",
|
||||
&ChunkedUploadOption{
|
||||
LookupJwtFunc: func(ctx context.Context, fileId string) security.EncodedJwt {
|
||||
token := tokens[lookups]
|
||||
lookups++
|
||||
return token
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
if lookups != 2 {
|
||||
t.Fatalf("expected a renewal per rejecting holder, got %d", lookups)
|
||||
}
|
||||
if atomic.LoadInt32(&acceptedDeletes) != 1 {
|
||||
t.Fatalf("expected the second holder's retried delete to land, got %d", acceptedDeletes)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package s3api
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"container/heap"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
@@ -1293,15 +1292,7 @@ func (s3a *S3ApiServer) listMultipartUploads(input *s3.ListMultipartUploadsInput
|
||||
|
||||
glog.V(2).Infof("listMultipartUploads input %v", input)
|
||||
|
||||
uploadsFolder := s3a.genUploadsFolder(*input.Bucket)
|
||||
var page *multipartUploadPage
|
||||
err := listRetry(uploadsFolder, func() error {
|
||||
page = newMultipartUploadPage(input)
|
||||
return filer_pb.List(context.Background(), s3a, uploadsFolder, "", func(entry *filer_pb.Entry, isLastEntry bool) error {
|
||||
page.add(entry)
|
||||
return nil
|
||||
}, "", false, math.MaxInt32)
|
||||
})
|
||||
entries, _, err := s3a.list(s3a.genUploadsFolder(*input.Bucket), "", "", false, math.MaxInt32)
|
||||
if err != nil {
|
||||
// A missing .uploads folder normally lists as empty with no error; a
|
||||
// store that reports it as not-found still means an empty list.
|
||||
@@ -1313,104 +1304,55 @@ func (s3a *S3ApiServer) listMultipartUploads(input *s3.ListMultipartUploadsInput
|
||||
return nil, s3err.ErrInternalError
|
||||
}
|
||||
|
||||
return page.result(), s3err.ErrNone
|
||||
return selectMultipartUploads(input, entries), s3err.ErrNone
|
||||
}
|
||||
|
||||
// selectMultipartUploads orders uploads by key, then by upload id, and resumes
|
||||
// after the (key-marker, upload-id-marker) position, so an aborted marker
|
||||
// upload does not hide the rest of its key.
|
||||
func selectMultipartUploads(input *s3.ListMultipartUploadsInput, entries []*filer_pb.Entry) *ListMultipartUploadsResult {
|
||||
page := newMultipartUploadPage(input)
|
||||
for _, entry := range entries {
|
||||
page.add(entry)
|
||||
}
|
||||
return page.result()
|
||||
}
|
||||
|
||||
// multipartUploadPage accumulates one page of a ListMultipartUploads result.
|
||||
// Upload order is the object key kept in extended attributes, not the upload
|
||||
// id the filer sorts by, so every entry has to be seen; keeping only the
|
||||
// maxUploads smallest candidates bounds the heap by the page, not the folder.
|
||||
type multipartUploadPage struct {
|
||||
input *s3.ListMultipartUploadsInput
|
||||
limit int
|
||||
top candidateHeap
|
||||
more bool
|
||||
}
|
||||
|
||||
type multipartCandidate struct {
|
||||
key string
|
||||
entry *filer_pb.Entry
|
||||
}
|
||||
|
||||
func compareMultipartCandidate(a, b multipartCandidate) int {
|
||||
return cmp.Or(strings.Compare(a.key, b.key), strings.Compare(a.entry.Name, b.entry.Name))
|
||||
}
|
||||
|
||||
// candidateHeap is a max-heap on (key, upload id): the root sorts last of the
|
||||
// candidates held, so popping it keeps the page's smallest entries.
|
||||
type candidateHeap []multipartCandidate
|
||||
|
||||
func (h candidateHeap) Len() int { return len(h) }
|
||||
func (h candidateHeap) Less(i, j int) bool {
|
||||
return compareMultipartCandidate(h[i], h[j]) > 0
|
||||
}
|
||||
func (h candidateHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
|
||||
func (h *candidateHeap) Push(x any) { *h = append(*h, x.(multipartCandidate)) }
|
||||
func (h *candidateHeap) Pop() any {
|
||||
old := *h
|
||||
n := len(old)
|
||||
*h = old[:n-1]
|
||||
return old[n-1]
|
||||
}
|
||||
|
||||
func newMultipartUploadPage(input *s3.ListMultipartUploadsInput) *multipartUploadPage {
|
||||
limit := maxUploadsList
|
||||
if *input.MaxUploads < int64(limit) {
|
||||
limit = int(*input.MaxUploads)
|
||||
}
|
||||
return &multipartUploadPage{input: input, limit: limit}
|
||||
}
|
||||
|
||||
func (p *multipartUploadPage) add(entry *filer_pb.Entry) {
|
||||
if p.limit <= 0 || !isMultipartUploadEntry(entry) {
|
||||
return
|
||||
}
|
||||
input := p.input
|
||||
key := *objectKey(aws.String(string(entry.Extended[s3_constants.ExtMultipartObjectKey])))
|
||||
if *input.Prefix != "" && !strings.HasPrefix(key, *input.Prefix) {
|
||||
return
|
||||
}
|
||||
if *input.KeyMarker != "" && (key < *input.KeyMarker || key == *input.KeyMarker && (*input.UploadIdMarker == "" || entry.Name <= *input.UploadIdMarker)) {
|
||||
return
|
||||
}
|
||||
c := multipartCandidate{key: key, entry: entry}
|
||||
if p.top.Len() >= p.limit {
|
||||
p.more = true
|
||||
if compareMultipartCandidate(c, p.top[0]) >= 0 {
|
||||
return
|
||||
}
|
||||
heap.Pop(&p.top)
|
||||
}
|
||||
heap.Push(&p.top, c)
|
||||
}
|
||||
|
||||
func (p *multipartUploadPage) result() *ListMultipartUploadsResult {
|
||||
input := p.input
|
||||
output := &ListMultipartUploadsResult{
|
||||
Bucket: input.Bucket,
|
||||
Delimiter: input.Delimiter,
|
||||
EncodingType: input.EncodingType,
|
||||
KeyMarker: input.KeyMarker,
|
||||
MaxUploads: aws.Int64(int64(p.limit)),
|
||||
MaxUploads: input.MaxUploads,
|
||||
Prefix: input.Prefix,
|
||||
UploadIdMarker: input.UploadIdMarker,
|
||||
IsTruncated: aws.Bool(false),
|
||||
}
|
||||
candidates := make([]multipartCandidate, len(p.top))
|
||||
copy(candidates, p.top)
|
||||
slices.SortFunc(candidates, compareMultipartCandidate)
|
||||
if *input.MaxUploads <= 0 {
|
||||
return output
|
||||
}
|
||||
type candidate struct {
|
||||
key string
|
||||
entry *filer_pb.Entry
|
||||
}
|
||||
var candidates []candidate
|
||||
for _, entry := range entries {
|
||||
if !isMultipartUploadEntry(entry) {
|
||||
continue
|
||||
}
|
||||
key := *objectKey(aws.String(string(entry.Extended[s3_constants.ExtMultipartObjectKey])))
|
||||
if *input.Prefix != "" && !strings.HasPrefix(key, *input.Prefix) {
|
||||
continue
|
||||
}
|
||||
if *input.KeyMarker != "" && (key < *input.KeyMarker || key == *input.KeyMarker && (*input.UploadIdMarker == "" || entry.Name <= *input.UploadIdMarker)) {
|
||||
continue
|
||||
}
|
||||
candidates = append(candidates, candidate{key: key, entry: entry})
|
||||
}
|
||||
slices.SortFunc(candidates, func(a, b candidate) int {
|
||||
return cmp.Or(strings.Compare(a.key, b.key), strings.Compare(a.entry.Name, b.entry.Name))
|
||||
})
|
||||
|
||||
for _, c := range candidates {
|
||||
if int64(len(output.Upload)) >= *input.MaxUploads {
|
||||
last := output.Upload[len(output.Upload)-1]
|
||||
output.IsTruncated = aws.Bool(true)
|
||||
output.NextKeyMarker, output.NextUploadIdMarker = last.Key, last.UploadId
|
||||
return output
|
||||
}
|
||||
upload := &s3.MultipartUpload{
|
||||
Key: aws.String(c.key),
|
||||
UploadId: aws.String(c.entry.Name),
|
||||
@@ -1420,11 +1362,6 @@ func (p *multipartUploadPage) result() *ListMultipartUploadsResult {
|
||||
}
|
||||
output.Upload = append(output.Upload, upload)
|
||||
}
|
||||
if p.more {
|
||||
last := output.Upload[len(output.Upload)-1]
|
||||
output.IsTruncated = aws.Bool(true)
|
||||
output.NextKeyMarker, output.NextUploadIdMarker = last.Key, last.UploadId
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
@@ -11,8 +8,6 @@ import (
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// uploadEntry is an upload folder as createMultipartUpload leaves it.
|
||||
@@ -117,84 +112,3 @@ func TestSelectMultipartUploadsPaginatesEveryUploadOnce(t *testing.T) {
|
||||
t.Fatalf("listed %d of %d uploads", len(seen), len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectMultipartUploadsHoldsOnlyThePage(t *testing.T) {
|
||||
// a folder far larger than the page must not accumulate in the collector:
|
||||
// peak memory tracks maxUploads, not the open-upload count
|
||||
page := newMultipartUploadPage(listUploadsInput("", "", "", 3))
|
||||
const total = 20000
|
||||
for i := 0; i < total; i++ {
|
||||
page.add(uploadEntry(fmt.Sprintf("%05d", i), fmt.Sprintf("k%05d", total-1-i), int64(i)))
|
||||
}
|
||||
if page.top.Len() != 3 {
|
||||
t.Fatalf("collector holds %d candidates, want the 3-entry page", page.top.Len())
|
||||
}
|
||||
out := page.result()
|
||||
var got []string
|
||||
for _, u := range out.Upload {
|
||||
got = append(got, *u.Key+"/"+*u.UploadId)
|
||||
}
|
||||
want := []string{"k00000/19999", "k00001/19998", "k00002/19997"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("got %v, want %v", got, want)
|
||||
}
|
||||
if !*out.IsTruncated || *out.NextKeyMarker != "k00002" || *out.NextUploadIdMarker != "19997" {
|
||||
t.Fatalf("truncation markers got (%v, %v, %v)", *out.IsTruncated, *out.NextKeyMarker, *out.NextUploadIdMarker)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectMultipartUploadsCapsRequestedPageSize(t *testing.T) {
|
||||
// max-uploads is caller-controlled; the page stays bounded at the server cap
|
||||
page := newMultipartUploadPage(listUploadsInput("", "", "", 10*maxUploadsList))
|
||||
if page.limit != maxUploadsList {
|
||||
t.Fatalf("page limit %d, want capped at %d", page.limit, maxUploadsList)
|
||||
}
|
||||
if got := *page.result().MaxUploads; got != int64(maxUploadsList) {
|
||||
t.Fatalf("MaxUploads reports %d, want the effective cap %d", got, maxUploadsList)
|
||||
}
|
||||
}
|
||||
|
||||
// A transient failure mid-stream replays through a fresh page, so the uploads
|
||||
// the aborted attempt already handed to the collector must not bleed into the
|
||||
// result: each upload lists once and the markers track the retried attempt.
|
||||
func TestListMultipartUploadsRetryCollectsEachUploadOnce(t *testing.T) {
|
||||
entries := []*filer_pb.Entry{
|
||||
uploadEntry("1", "c", 10),
|
||||
uploadEntry("2", "a", 30),
|
||||
uploadEntry("3", "b", 10),
|
||||
}
|
||||
client := &listRetryClient{
|
||||
entries: entries,
|
||||
recvErrs: []error{status.Error(codes.Unavailable, "transport is closing"), nil},
|
||||
recvAfter: []int{2, 0},
|
||||
}
|
||||
accessor := &listRetryAccessor{client: client}
|
||||
input := listUploadsInput("", "", "", 2)
|
||||
|
||||
var page *multipartUploadPage
|
||||
err := listRetry("/buckets/b/.uploads", func() error {
|
||||
page = newMultipartUploadPage(input)
|
||||
return filer_pb.List(context.Background(), accessor, "/buckets/b/.uploads", "", func(entry *filer_pb.Entry, isLastEntry bool) error {
|
||||
page.add(entry)
|
||||
return nil
|
||||
}, "", false, math.MaxInt32)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("listRetry: %v", err)
|
||||
}
|
||||
if client.attempts != 2 {
|
||||
t.Fatalf("got %d attempts, want 2", client.attempts)
|
||||
}
|
||||
out := page.result()
|
||||
var got []string
|
||||
for _, u := range out.Upload {
|
||||
got = append(got, *u.Key+"/"+*u.UploadId)
|
||||
}
|
||||
want := []string{"a/2", "b/3"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("got %v, want %v (no entry from the aborted attempt may carry over)", got, want)
|
||||
}
|
||||
if !*out.IsTruncated || *out.NextKeyMarker != "b" || *out.NextUploadIdMarker != "3" {
|
||||
t.Fatalf("truncation markers got (%v, %v, %v)", *out.IsTruncated, *out.NextKeyMarker, *out.NextUploadIdMarker)
|
||||
}
|
||||
}
|
||||
@@ -93,17 +93,17 @@ func isRetryableListError(err error) bool {
|
||||
return err != nil && !isFilerNotFound(err) && util.IsTransientError(err)
|
||||
}
|
||||
|
||||
// listRetry replays doList while the filer answers with a transient error.
|
||||
// listWithRetry replays doList while the filer answers with a transient error.
|
||||
// Both failure points, the ListEntries call itself and the stream.Recv that
|
||||
// follows it, surface as a plain error out of filer_pb.List, so a single retry
|
||||
// point above it covers both. A replayed attempt may re-deliver entries the
|
||||
// last attempt already saw, so a doList that accumulates must reset first.
|
||||
func listRetry(parentDirectoryPath string, doList func() error) (err error) {
|
||||
// point above it covers both.
|
||||
func listWithRetry(parentDirectoryPath string, doList func() (entries []*filer_pb.Entry, isLast bool, err error)) (entries []*filer_pb.Entry, isLast bool, err error) {
|
||||
|
||||
backoff := listRetryInitialBackoff
|
||||
for attempt := 1; ; attempt++ {
|
||||
if err = doList(); err == nil || attempt >= listRetryAttempts || !isRetryableListError(err) {
|
||||
return err
|
||||
entries, isLast, err = doList()
|
||||
if err == nil || attempt >= listRetryAttempts || !isRetryableListError(err) {
|
||||
return entries, isLast, err
|
||||
}
|
||||
glog.V(1).Infof("list %s attempt %d/%d hit a transient error, retrying in %v: %v", parentDirectoryPath, attempt, listRetryAttempts, backoff, err)
|
||||
time.Sleep(backoff)
|
||||
@@ -112,16 +112,6 @@ func listRetry(parentDirectoryPath string, doList func() error) (err error) {
|
||||
|
||||
}
|
||||
|
||||
func listWithRetry(parentDirectoryPath string, doList func() (entries []*filer_pb.Entry, isLast bool, err error)) (entries []*filer_pb.Entry, isLast bool, err error) {
|
||||
|
||||
err = listRetry(parentDirectoryPath, func() error {
|
||||
entries, isLast, err = doList()
|
||||
return err
|
||||
})
|
||||
return entries, isLast, err
|
||||
|
||||
}
|
||||
|
||||
// A delete is idempotent at the filer, which answers an entry that is already
|
||||
// gone with an empty resp.Error, so a reply the transport dropped can be
|
||||
// reissued instead of surfaced: as a 500 on the bucket delete, or as a per-key
|
||||
|
||||
@@ -696,7 +696,6 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
|
||||
MimeType: r.Header.Get("Content-Type"),
|
||||
Cipher: s3a.cipher, // encrypt data on volume servers
|
||||
AssignFunc: assignFunc,
|
||||
LookupJwtFunc: s3a.lookupVolumeJwt,
|
||||
})
|
||||
if err != nil {
|
||||
glog.Errorf("putToFiler: chunked upload failed: %v", err)
|
||||
@@ -3023,15 +3022,6 @@ func (s3a *S3ApiServer) checkConditionalHeadersForReads(r *http.Request, bucket,
|
||||
return s3a.validateConditionalHeadersForReads(r, headers, entry, bucket, object)
|
||||
}
|
||||
|
||||
// lookupVolumeJwt mints a fresh volume-server JWT for an existing file id, so a
|
||||
// cleanup delete that runs past the assignment JWT's expiry still authenticates.
|
||||
func (s3a *S3ApiServer) lookupVolumeJwt(ctx context.Context, fileId string) security.EncodedJwt {
|
||||
if s3a.masterClient == nil {
|
||||
return ""
|
||||
}
|
||||
return operation.LookupJwt(ctx, s3a.masterClient.GetMaster(ctx), s3a.option.GrpcDialOption, fileId)
|
||||
}
|
||||
|
||||
// deleteOrphanedChunks attempts to delete chunks that were uploaded but whose entry creation failed
|
||||
// This prevents resource leaks and wasted storage. Errors are logged but don't prevent cleanup attempts.
|
||||
func (s3a *S3ApiServer) deleteOrphanedChunks(chunks []*filer_pb.FileChunk) {
|
||||
|
||||
@@ -105,7 +105,6 @@ type S3ApiServer struct {
|
||||
randomClientId int32
|
||||
filerGuard *security.Guard
|
||||
filerClient *wdclient.FilerClient
|
||||
masterClient *wdclient.MasterClient
|
||||
client util_http_client.HTTPClientInterface
|
||||
bucketRegistry *BucketRegistry
|
||||
credentialManager *credential.CredentialManager
|
||||
@@ -346,7 +345,6 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
randomClientId: util.RandomInt32(),
|
||||
filerGuard: security.NewGuard([]string{}, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec),
|
||||
filerClient: filerClient,
|
||||
masterClient: masterClient,
|
||||
cb: NewCircuitBreaker(option),
|
||||
credentialManager: iam.credentialManager,
|
||||
bucketConfigCache: NewBucketConfigCache(60 * time.Minute), // Increased TTL since cache is now event-driven
|
||||
|
||||
@@ -7,12 +7,10 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -99,7 +97,6 @@ func TestAssumeRoleWithWebIdentityOverHTTP(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{iamIntegration: NewS3IAMIntegration(manager, "")}
|
||||
handlers := NewSTSHandlers(manager.GetSTSService(), iam)
|
||||
|
||||
var jtiCounter atomic.Int64
|
||||
signOIDCToken := func(t *testing.T, subject string) string {
|
||||
t.Helper()
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
|
||||
@@ -108,10 +105,6 @@ func TestAssumeRoleWithWebIdentityOverHTTP(t *testing.T) {
|
||||
"aud": "test-client",
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
// a unique jti per token: the exchange consumes it, so two
|
||||
// subtests minting the same claims in one second would otherwise
|
||||
// collide on the token fingerprint and read as a replay
|
||||
"jti": fmt.Sprintf("%s-%d", subject, jtiCounter.Add(1)),
|
||||
})
|
||||
token.Header["kid"] = "web-identity-test-key"
|
||||
signed, err := token.SignedString(key)
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
var (
|
||||
MAJOR_VERSION = int32(4)
|
||||
MINOR_VERSION = int32(49)
|
||||
MINOR_VERSION = int32(48)
|
||||
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
|
||||
VERSION = util.SizeLimit + " " + VERSION_NUMBER
|
||||
COMMIT = ""
|
||||
|
||||
@@ -455,60 +455,39 @@ func (t *ErasureCodingTask) rollbackReadonly(_ context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// ecCopyAttempts bounds how often the pinned file pair copy restarts after a
|
||||
// concurrent compaction bumps the source's CompactionRevision mid-copy.
|
||||
const ecCopyAttempts = 3
|
||||
|
||||
// copyVolumeFilesToWorker copies .idx and .dat files from source server to local worker.
|
||||
// The .idx is copied first, then .dat. Both copies are capped to the sizes reported by
|
||||
// ReadVolumeFileStatus and pinned to its CompactionRevision so they come from the same
|
||||
// volume generation. A concurrent vacuum bumps that revision mid-copy, so a compaction
|
||||
// failure restarts the pair under a freshly read revision.
|
||||
// ReadVolumeFileStatus. If a write lands after .idx is copied, .dat may include extra
|
||||
// data not referenced by .idx (harmless). The reverse (idx referencing data past .dat)
|
||||
// is caught by verifyDatIdxConsistency in generateEcShardsLocally.
|
||||
func (t *ErasureCodingTask) copyVolumeFilesToWorker(ctx context.Context, workDir string) (map[string]string, error) {
|
||||
localFiles := make(map[string]string)
|
||||
|
||||
var copyErr error
|
||||
for attempt := 0; attempt < ecCopyAttempts; attempt++ {
|
||||
fileStatus, err := t.readSourceVolumeFileStatus(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read source volume file status: %w", err)
|
||||
}
|
||||
t.expireAtSec = fileStatus.GetExpireAtSec()
|
||||
if t.expireAtSec == 0 {
|
||||
// Volume servers that predate the top-level field still carry the
|
||||
// expiry in the nested .vif once SaveVolumeInfo has stamped it.
|
||||
t.expireAtSec = fileStatus.GetVolumeInfo().GetExpireAtSec()
|
||||
}
|
||||
|
||||
t.GetLogger().WithFields(map[string]interface{}{
|
||||
"volume_id": t.volumeID,
|
||||
"source": t.server,
|
||||
"working_dir": workDir,
|
||||
"compaction_revision": fileStatus.GetCompactionRevision(),
|
||||
"dat_file_size_bytes": fileStatus.GetDatFileSize(),
|
||||
"idx_file_size_bytes": fileStatus.GetIdxFileSize(),
|
||||
}).Info("Starting volume file copy from source server")
|
||||
|
||||
if copyErr = t.copyVolumeFilePair(ctx, workDir, fileStatus, localFiles); copyErr == nil {
|
||||
return localFiles, nil
|
||||
}
|
||||
if !isVolumeCompactedError(copyErr) || ctx.Err() != nil {
|
||||
return nil, copyErr
|
||||
}
|
||||
glog.Warningf("volume %d on %s compacted during EC file copy, restarting with fresh file status: %v", t.volumeID, t.server, copyErr)
|
||||
fileStatus, err := t.readSourceVolumeFileStatus(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read source volume file status: %w", err)
|
||||
}
|
||||
t.expireAtSec = fileStatus.GetExpireAtSec()
|
||||
if t.expireAtSec == 0 {
|
||||
// Volume servers that predate the top-level field still carry the
|
||||
// expiry in the nested .vif once SaveVolumeInfo has stamped it.
|
||||
t.expireAtSec = fileStatus.GetVolumeInfo().GetExpireAtSec()
|
||||
}
|
||||
return nil, copyErr
|
||||
}
|
||||
|
||||
// copyVolumeFilePair copies .idx first, then .dat, pinned to the compaction
|
||||
// revision in fileStatus. If a write lands after .idx is copied, .dat may
|
||||
// include extra data not referenced by .idx (harmless). The reverse (idx
|
||||
// referencing data past .dat) is caught by verifyDatIdxConsistency in
|
||||
// generateEcShardsLocally.
|
||||
func (t *ErasureCodingTask) copyVolumeFilePair(ctx context.Context, workDir string, fileStatus *volume_server_pb.ReadVolumeFileStatusResponse, localFiles map[string]string) error {
|
||||
t.GetLogger().WithFields(map[string]interface{}{
|
||||
"volume_id": t.volumeID,
|
||||
"source": t.server,
|
||||
"working_dir": workDir,
|
||||
"compaction_revision": fileStatus.GetCompactionRevision(),
|
||||
"dat_file_size_bytes": fileStatus.GetDatFileSize(),
|
||||
"idx_file_size_bytes": fileStatus.GetIdxFileSize(),
|
||||
}).Info("Starting volume file copy from source server")
|
||||
|
||||
// Copy .idx file FIRST — if a write lands on the source after this copy,
|
||||
// the .dat copy will include the new data but .idx won't reference it.
|
||||
idxFile := filepath.Join(workDir, fmt.Sprintf("%d.idx", t.volumeID))
|
||||
if err := t.copyFileFromSource(ctx, ".idx", idxFile, fileStatus.GetCompactionRevision(), fileStatus.GetIdxFileSize()); err != nil {
|
||||
return fmt.Errorf("failed to copy .idx file: %w", err)
|
||||
return nil, fmt.Errorf("failed to copy .idx file: %w", err)
|
||||
}
|
||||
localFiles["idx"] = idxFile
|
||||
|
||||
@@ -524,7 +503,7 @@ func (t *ErasureCodingTask) copyVolumeFilePair(ctx context.Context, workDir stri
|
||||
// Copy .dat file SECOND — guaranteed to have at least as much data as .idx references.
|
||||
datFile := filepath.Join(workDir, fmt.Sprintf("%d.dat", t.volumeID))
|
||||
if err := t.copyFileFromSource(ctx, ".dat", datFile, fileStatus.GetCompactionRevision(), fileStatus.GetDatFileSize()); err != nil {
|
||||
return fmt.Errorf("failed to copy .dat file: %w", err)
|
||||
return nil, fmt.Errorf("failed to copy .dat file: %w", err)
|
||||
}
|
||||
localFiles["dat"] = datFile
|
||||
|
||||
@@ -537,13 +516,7 @@ func (t *ErasureCodingTask) copyVolumeFilePair(ctx context.Context, workDir stri
|
||||
}).Info("Volume data file copied successfully")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// isVolumeCompactedError matches the failure CopyFile returns when the source
|
||||
// volume's CompactionRevision moved past the pinned one mid-copy.
|
||||
func isVolumeCompactedError(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), "is compacted")
|
||||
return localFiles, nil
|
||||
}
|
||||
|
||||
func (t *ErasureCodingTask) readSourceVolumeFileStatus(ctx context.Context) (*volume_server_pb.ReadVolumeFileStatusResponse, error) {
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// fakeCopySource is a stub VolumeServer. Rejecting a pinned .dat copy advances
|
||||
// the compaction revision and rewrites the volume contents, so a mid-copy
|
||||
// compaction is replayed deterministically.
|
||||
type fakeCopySource struct {
|
||||
volume_server_pb.UnimplementedVolumeServerServer
|
||||
|
||||
mu sync.Mutex
|
||||
revision uint32
|
||||
datBytes []byte
|
||||
idxBytes []byte
|
||||
expireAtSec uint64
|
||||
rejectDat int
|
||||
failErr error
|
||||
statusCalls int
|
||||
copyCalls int
|
||||
}
|
||||
|
||||
func (f *fakeCopySource) snapshot() (revision uint32, expireAtSec uint64, statusCalls, copyCalls int) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.revision, f.expireAtSec, f.statusCalls, f.copyCalls
|
||||
}
|
||||
|
||||
func (f *fakeCopySource) ReadVolumeFileStatus(context.Context, *volume_server_pb.ReadVolumeFileStatusRequest) (*volume_server_pb.ReadVolumeFileStatusResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.statusCalls++
|
||||
return &volume_server_pb.ReadVolumeFileStatusResponse{
|
||||
CompactionRevision: f.revision,
|
||||
DatFileSize: uint64(len(f.datBytes)),
|
||||
IdxFileSize: uint64(len(f.idxBytes)),
|
||||
ExpireAtSec: f.expireAtSec,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (f *fakeCopySource) CopyFile(req *volume_server_pb.CopyFileRequest, stream grpc.ServerStreamingServer[volume_server_pb.CopyFileResponse]) error {
|
||||
f.mu.Lock()
|
||||
f.copyCalls++
|
||||
reject := req.GetExt() == ".dat" && f.rejectDat > 0
|
||||
if reject {
|
||||
f.rejectDat--
|
||||
f.revision++
|
||||
f.datBytes = append(f.datBytes, 0xEC)
|
||||
f.idxBytes = append(f.idxBytes, 0xEC)
|
||||
f.expireAtSec += 100
|
||||
}
|
||||
failErr := f.failErr
|
||||
revision := f.revision
|
||||
var content []byte
|
||||
switch req.GetExt() {
|
||||
case ".idx":
|
||||
content = f.idxBytes
|
||||
case ".dat":
|
||||
content = f.datBytes
|
||||
}
|
||||
f.mu.Unlock()
|
||||
|
||||
if failErr != nil {
|
||||
return failErr
|
||||
}
|
||||
if reject || req.GetCompactionRevision() != revision {
|
||||
return fmt.Errorf("volume %d is compacted", req.GetVolumeId())
|
||||
}
|
||||
content = content[:req.GetStopOffset()]
|
||||
for len(content) > 0 {
|
||||
n := min(len(content), 4)
|
||||
if err := stream.Send(&volume_server_pb.CopyFileResponse{FileContent: content[:n]}); err != nil {
|
||||
return err
|
||||
}
|
||||
content = content[n:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func startFakeCopySource(t *testing.T, src *fakeCopySource) string {
|
||||
t.Helper()
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
grpcServer := grpc.NewServer()
|
||||
volume_server_pb.RegisterVolumeServerServer(grpcServer, src)
|
||||
go grpcServer.Serve(lis)
|
||||
t.Cleanup(grpcServer.Stop)
|
||||
// server addresses carry httpPort.grpcPort; the gRPC dialer uses the part
|
||||
// after the dot, so report the listening port that way
|
||||
_, port, err := net.SplitHostPort(lis.Addr().String())
|
||||
require.NoError(t, err)
|
||||
return "127.0.0.1:0." + port
|
||||
}
|
||||
|
||||
func newCopyRetryTask(addr string) *ErasureCodingTask {
|
||||
return NewErasureCodingTask("copy-retry", addr, 951, "", grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
}
|
||||
|
||||
func TestCopyVolumeFilesToWorkerRetriesAfterMidCopyCompaction(t *testing.T) {
|
||||
src := &fakeCopySource{
|
||||
revision: 7,
|
||||
idxBytes: []byte("idx-data-v7"),
|
||||
datBytes: []byte("dat-payload-v7"),
|
||||
expireAtSec: 1000,
|
||||
rejectDat: 1,
|
||||
}
|
||||
task := newCopyRetryTask(startFakeCopySource(t, src))
|
||||
|
||||
localFiles, err := task.copyVolumeFilesToWorker(context.Background(), t.TempDir())
|
||||
require.NoError(t, err)
|
||||
|
||||
datContent, err := os.ReadFile(localFiles["dat"])
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("dat-payload-v7\xEC"), datContent)
|
||||
idxContent, err := os.ReadFile(localFiles["idx"])
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("idx-data-v7\xEC"), idxContent)
|
||||
revision, expireAtSec, statusCalls, copyCalls := src.snapshot()
|
||||
require.Equal(t, uint32(8), revision)
|
||||
require.Equal(t, 2, statusCalls)
|
||||
require.Equal(t, 4, copyCalls)
|
||||
require.Equal(t, expireAtSec, task.expireAtSec)
|
||||
}
|
||||
|
||||
func TestCopyVolumeFilesToWorkerStopsAfterRetryLimit(t *testing.T) {
|
||||
src := &fakeCopySource{
|
||||
revision: 1,
|
||||
idxBytes: []byte("i"),
|
||||
datBytes: []byte("d"),
|
||||
rejectDat: 10,
|
||||
}
|
||||
task := newCopyRetryTask(startFakeCopySource(t, src))
|
||||
|
||||
_, err := task.copyVolumeFilesToWorker(context.Background(), t.TempDir())
|
||||
require.ErrorContains(t, err, "is compacted")
|
||||
_, _, statusCalls, copyCalls := src.snapshot()
|
||||
require.Equal(t, ecCopyAttempts, statusCalls)
|
||||
require.Equal(t, 2*ecCopyAttempts, copyCalls)
|
||||
}
|
||||
|
||||
func TestCopyVolumeFilesToWorkerReturnsNonCompactionErrors(t *testing.T) {
|
||||
src := &fakeCopySource{
|
||||
revision: 1,
|
||||
idxBytes: []byte("i"),
|
||||
datBytes: []byte("d"),
|
||||
failErr: fmt.Errorf("boom"),
|
||||
}
|
||||
task := newCopyRetryTask(startFakeCopySource(t, src))
|
||||
|
||||
_, err := task.copyVolumeFilesToWorker(context.Background(), t.TempDir())
|
||||
require.ErrorContains(t, err, "boom")
|
||||
_, _, statusCalls, copyCalls := src.snapshot()
|
||||
require.Equal(t, 1, statusCalls)
|
||||
require.Equal(t, 1, copyCalls)
|
||||
}
|
||||
Reference in new issue
Block a user