mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63c218c399 | ||
|
|
3b4690d1b7 | ||
|
|
9a7f033d7f | ||
|
|
780760fccc | ||
|
|
a3e97ec709 | ||
|
|
23d8c62844 | ||
|
|
4bdbfbaaa8 | ||
|
|
e73c23a4ee | ||
|
|
8c3d8fcea0 | ||
|
|
bb1ba8b247 | ||
|
|
593cfee85b | ||
|
|
03065155db |
No files matched your search
@@ -268,8 +268,10 @@ async fn refresh_leader_from_peers(
|
||||
state: &Arc<VolumeServerState>,
|
||||
timeout: Duration,
|
||||
) {
|
||||
let lookup =
|
||||
lookup_leader_from_peers(&config.master_addresses, state.outgoing_grpc_tls.as_ref());
|
||||
let lookup = lookup_leader_from_peers(
|
||||
&config.master_addresses,
|
||||
state.outgoing_grpc_tls.as_ref(),
|
||||
);
|
||||
match tokio::time::timeout(timeout, lookup).await {
|
||||
Ok(Some(leader)) => publish_current_master(state, &leader).await,
|
||||
_ => state.current_master_url.write().await.clear(),
|
||||
@@ -3030,385 +3032,4 @@ mod tests {
|
||||
assert_eq!(deleted_after_delete[0].ec_index_bits, 1);
|
||||
assert_eq!(deleted_after_delete[0].shard_sizes, vec![0]);
|
||||
}
|
||||
|
||||
/// A master gRPC stub for the leader-tracking tests: every RPC except the
|
||||
/// two the tests drive is unimplemented. `leader` is what
|
||||
/// GetMasterConfiguration names; `replies` are what the heartbeat stream
|
||||
/// sends before closing.
|
||||
struct FakeMaster {
|
||||
leader: String,
|
||||
replies: Vec<master_pb::HeartbeatResponse>,
|
||||
}
|
||||
|
||||
#[tonic::async_trait]
|
||||
impl master_pb::seaweed_server::Seaweed for FakeMaster {
|
||||
type SendHeartbeatStream = tokio_stream::Iter<
|
||||
std::vec::IntoIter<Result<master_pb::HeartbeatResponse, tonic::Status>>,
|
||||
>;
|
||||
type KeepConnectedStream = tokio_stream::Iter<
|
||||
std::vec::IntoIter<Result<master_pb::KeepConnectedResponse, tonic::Status>>,
|
||||
>;
|
||||
type StreamAssignStream = tokio_stream::Iter<
|
||||
std::vec::IntoIter<Result<master_pb::AssignResponse, tonic::Status>>,
|
||||
>;
|
||||
type VolumeListStreamStream = tokio_stream::Iter<
|
||||
std::vec::IntoIter<Result<master_pb::VolumeListStreamResponse, tonic::Status>>,
|
||||
>;
|
||||
|
||||
async fn send_heartbeat(
|
||||
&self,
|
||||
_request: tonic::Request<tonic::Streaming<master_pb::Heartbeat>>,
|
||||
) -> std::result::Result<tonic::Response<Self::SendHeartbeatStream>, tonic::Status>
|
||||
{
|
||||
Ok(tonic::Response::new(tokio_stream::iter(
|
||||
self.replies.iter().cloned().map(Ok).collect::<Vec<_>>(),
|
||||
)))
|
||||
}
|
||||
|
||||
async fn keep_connected(
|
||||
&self,
|
||||
_request: tonic::Request<tonic::Streaming<master_pb::KeepConnectedRequest>>,
|
||||
) -> std::result::Result<tonic::Response<Self::KeepConnectedStream>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("keep_connected"))
|
||||
}
|
||||
|
||||
async fn stream_assign(
|
||||
&self,
|
||||
_request: tonic::Request<tonic::Streaming<master_pb::AssignRequest>>,
|
||||
) -> std::result::Result<tonic::Response<Self::StreamAssignStream>, tonic::Status> {
|
||||
Err(tonic::Status::unimplemented("stream_assign"))
|
||||
}
|
||||
|
||||
async fn get_master_configuration(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::GetMasterConfigurationRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::GetMasterConfigurationResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Ok(tonic::Response::new(
|
||||
master_pb::GetMasterConfigurationResponse {
|
||||
leader: self.leader.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
async fn lookup_volume(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::LookupVolumeRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::LookupVolumeResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("lookup_volume"))
|
||||
}
|
||||
|
||||
async fn assign(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::AssignRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::AssignResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("assign"))
|
||||
}
|
||||
|
||||
async fn statistics(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::StatisticsRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::StatisticsResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("statistics"))
|
||||
}
|
||||
|
||||
async fn collection_list(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::CollectionListRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::CollectionListResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("collection_list"))
|
||||
}
|
||||
|
||||
async fn collection_delete(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::CollectionDeleteRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::CollectionDeleteResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("collection_delete"))
|
||||
}
|
||||
|
||||
async fn volume_list(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::VolumeListRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::VolumeListResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("volume_list"))
|
||||
}
|
||||
|
||||
async fn volume_list_stream(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::VolumeListRequest>,
|
||||
) -> std::result::Result<tonic::Response<Self::VolumeListStreamStream>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("volume_list_stream"))
|
||||
}
|
||||
|
||||
async fn lookup_ec_volume(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::LookupEcVolumeRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::LookupEcVolumeResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("lookup_ec_volume"))
|
||||
}
|
||||
|
||||
async fn vacuum_volume(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::VacuumVolumeRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::VacuumVolumeResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("vacuum_volume"))
|
||||
}
|
||||
|
||||
async fn disable_vacuum(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::DisableVacuumRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::DisableVacuumResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("disable_vacuum"))
|
||||
}
|
||||
|
||||
async fn enable_vacuum(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::EnableVacuumRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::EnableVacuumResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("enable_vacuum"))
|
||||
}
|
||||
|
||||
async fn volume_mark_readonly(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::VolumeMarkReadonlyRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::VolumeMarkReadonlyResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Err(tonic::Status::unimplemented("volume_mark_readonly"))
|
||||
}
|
||||
|
||||
async fn list_cluster_nodes(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::ListClusterNodesRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::ListClusterNodesResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("list_cluster_nodes"))
|
||||
}
|
||||
|
||||
async fn lease_admin_token(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::LeaseAdminTokenRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::LeaseAdminTokenResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("lease_admin_token"))
|
||||
}
|
||||
|
||||
async fn release_admin_token(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::ReleaseAdminTokenRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::ReleaseAdminTokenResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("release_admin_token"))
|
||||
}
|
||||
|
||||
async fn get_admin_lock_status(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::GetAdminLockStatusRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::GetAdminLockStatusResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Err(tonic::Status::unimplemented("get_admin_lock_status"))
|
||||
}
|
||||
|
||||
async fn ping(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::PingRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::PingResponse>, tonic::Status> {
|
||||
Err(tonic::Status::unimplemented("ping"))
|
||||
}
|
||||
|
||||
async fn raft_list_cluster_servers(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::RaftListClusterServersRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::RaftListClusterServersResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Err(tonic::Status::unimplemented("raft_list_cluster_servers"))
|
||||
}
|
||||
|
||||
async fn raft_add_server(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::RaftAddServerRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::RaftAddServerResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("raft_add_server"))
|
||||
}
|
||||
|
||||
async fn raft_remove_server(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::RaftRemoveServerRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::RaftRemoveServerResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("raft_remove_server"))
|
||||
}
|
||||
|
||||
async fn raft_leadership_transfer(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::RaftLeadershipTransferRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::RaftLeadershipTransferResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Err(tonic::Status::unimplemented("raft_leadership_transfer"))
|
||||
}
|
||||
|
||||
async fn resume_volume_growth(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::ResumeVolumeGrowthRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::ResumeVolumeGrowthResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Err(tonic::Status::unimplemented("resume_volume_growth"))
|
||||
}
|
||||
|
||||
async fn volume_grow(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::VolumeGrowRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::VolumeGrowResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("volume_grow"))
|
||||
}
|
||||
|
||||
async fn collection_statistics(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::CollectionStatisticsRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::CollectionStatisticsResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Err(tonic::Status::unimplemented("collection_statistics"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a FakeMaster on a loopback port, returning the `host:port` gRPC
|
||||
/// clients dial. The task stops with the test's runtime.
|
||||
async fn fake_master_addr(fake: FakeMaster) -> String {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
let _ = tonic::transport::Server::builder()
|
||||
.add_service(master_pb::seaweed_server::SeaweedServer::new(fake))
|
||||
.serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))
|
||||
.await;
|
||||
});
|
||||
format!("127.0.0.1:{port}")
|
||||
}
|
||||
|
||||
// Go's TestHeartbeatToFollowerPublishesNamedLeaderOnly: a reply that
|
||||
// names a different leader publishes it right away and ends the session
|
||||
// with the redirect — lookups stop landing on the follower.
|
||||
#[tokio::test]
|
||||
async fn test_heartbeat_to_a_follower_publishes_the_named_leader() {
|
||||
let grpc_addr = fake_master_addr(FakeMaster {
|
||||
leader: String::new(),
|
||||
replies: vec![master_pb::HeartbeatResponse {
|
||||
leader: "leader.example.com:9333".to_string(),
|
||||
..Default::default()
|
||||
}],
|
||||
})
|
||||
.await;
|
||||
let state = test_state_with_store(Store::new(NeedleMapKind::InMemory));
|
||||
let config = test_config();
|
||||
let (_shutdown_tx, mut shutdown_rx) = broadcast::channel(1);
|
||||
|
||||
let redirected = do_heartbeat(
|
||||
&config,
|
||||
&state,
|
||||
&grpc_addr,
|
||||
"127.0.0.1:0",
|
||||
Duration::from_millis(50),
|
||||
&mut shutdown_rx,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(redirected.as_deref(), Some("leader.example.com:9333"));
|
||||
assert_eq!(
|
||||
*state.current_master_url.read().await,
|
||||
"leader.example.com:9333"
|
||||
);
|
||||
}
|
||||
|
||||
// Go's TestHeartbeatToLeaderPublishesItAndResendsFromSendLoop, first
|
||||
// half: the first reply without a leader field is the leader's own, so
|
||||
// the connected peer becomes the lookup target.
|
||||
#[tokio::test]
|
||||
async fn test_heartbeat_to_the_leader_publishes_the_connected_peer() {
|
||||
let grpc_addr = fake_master_addr(FakeMaster {
|
||||
leader: String::new(),
|
||||
replies: vec![master_pb::HeartbeatResponse::default()],
|
||||
})
|
||||
.await;
|
||||
let state = test_state_with_store(Store::new(NeedleMapKind::InMemory));
|
||||
let config = test_config();
|
||||
let (_shutdown_tx, mut shutdown_rx) = broadcast::channel(1);
|
||||
|
||||
let redirected = do_heartbeat(
|
||||
&config,
|
||||
&state,
|
||||
&grpc_addr,
|
||||
"127.0.0.1:1",
|
||||
Duration::from_millis(50),
|
||||
&mut shutdown_rx,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(redirected.is_none());
|
||||
assert_eq!(*state.current_master_url.read().await, "127.0.0.1:1");
|
||||
}
|
||||
|
||||
// Go's TestRefreshLeaderFromPeersPublishesReportedLeader: after losing
|
||||
// the stream, the loop asks the configured masters who leads and
|
||||
// publishes the answer.
|
||||
#[tokio::test]
|
||||
async fn test_refresh_leader_from_peers_publishes_the_reported_leader() {
|
||||
let grpc_addr = fake_master_addr(FakeMaster {
|
||||
leader: "10.9.9.9:9333".to_string(),
|
||||
replies: vec![],
|
||||
})
|
||||
.await;
|
||||
let port = grpc_addr.rsplit(':').next().unwrap();
|
||||
let mut config = test_config();
|
||||
config.master_addresses = vec![format!("127.0.0.1:0.{port}")];
|
||||
let state = test_state_with_store(Store::new(NeedleMapKind::InMemory));
|
||||
|
||||
refresh_leader_from_peers(&config, &state, Duration::from_secs(5)).await;
|
||||
|
||||
assert_eq!(*state.current_master_url.read().await, "10.9.9.9:9333");
|
||||
}
|
||||
|
||||
// Go's TestRefreshLeaderFromPeersClearsLeaderWithoutAnswer: no peer
|
||||
// answering clears the published master — the lost one is dead or a
|
||||
// follower answering lookups from its own cache.
|
||||
#[tokio::test]
|
||||
async fn test_refresh_leader_from_peers_clears_without_an_answer() {
|
||||
let mut config = test_config();
|
||||
config.master_addresses = vec!["127.0.0.1:0.1".to_string()];
|
||||
let state = test_state_with_store(Store::new(NeedleMapKind::InMemory));
|
||||
*state.current_master_url.write().await = "dead.example.com:9333".to_string();
|
||||
|
||||
refresh_leader_from_peers(&config, &state, Duration::from_secs(2)).await;
|
||||
|
||||
assert!(state.current_master_url.read().await.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -384,6 +384,16 @@ func processUpdateEvent(
|
||||
}
|
||||
glog.V(0).Infof("never replicated, uploading %s", remote_storage.FormatLocation(dest))
|
||||
}
|
||||
if proto.Equal(oldDest, dest) && isDroppedLocalCopy(message.NewEntry) {
|
||||
// The update dropped the local copy: remote.uncache, eviction under
|
||||
// storage pressure, or remote.meta.sync pulling a newer remote
|
||||
// version. Each clears the sync stamp, so shouldSendToRemote reads
|
||||
// the entry as dirty when the remote mtime shares its second. The
|
||||
// content is the object at this very key, and uploading the chunkless
|
||||
// entry would replace it with zero bytes.
|
||||
glog.V(2).Infof("skipping update of remote-only entry: %+v", resp)
|
||||
return nil
|
||||
}
|
||||
glog.V(2).Infof("update: %+v", resp)
|
||||
if !proto.Equal(oldDest, dest) {
|
||||
// A renamed entry that holds no local data now (the snapshot was
|
||||
@@ -488,6 +498,15 @@ func isRemoteOnly(entry *filer_pb.Entry) bool {
|
||||
return entry != nil && !filer.HasData(entry) && entry.IsInRemoteOnly()
|
||||
}
|
||||
|
||||
// isDroppedLocalCopy reports a remote-only entry whose size is still the
|
||||
// remote object's: its local copy was dropped and the object describes it.
|
||||
// Uncache and eviction keep the size, and remote.meta.sync sets it from the
|
||||
// object. A truncate drops the chunks too but changes the size, and the
|
||||
// truncated content has to reach the remote.
|
||||
func isDroppedLocalCopy(entry *filer_pb.Entry) bool {
|
||||
return isRemoteOnly(entry) && entry.GetAttributes().GetFileSize() == uint64(entry.RemoteEntry.RemoteSize)
|
||||
}
|
||||
|
||||
// completeRemoteOnlyRename finishes a rename whose content exists only on the
|
||||
// remote. When the destination object already holds what the entry's stamp
|
||||
// describes (the rename ran before, its offset was not persisted, and
|
||||
|
||||
@@ -1722,6 +1722,206 @@ func TestMetadataOnlyUpdateRestampsSyncTs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The droppedCopy fixtures are a small synced file under a mount: a Delta log
|
||||
// entry whose remote object was written in the second of its mtime, as a quick
|
||||
// sync of a small file is.
|
||||
const droppedCopyMtime = 1786096669
|
||||
|
||||
var (
|
||||
droppedCopyDir = "/buckets/gold/sales/_delta_log"
|
||||
droppedCopyName = "00000000000000000007.json"
|
||||
droppedCopyMount = &remote_pb.RemoteStorageLocation{Name: "s3", Bucket: "gold", Path: "/"}
|
||||
droppedCopyDest = &remote_pb.RemoteStorageLocation{Name: "s3", Bucket: "gold", Path: "/sales/_delta_log/" + droppedCopyName}
|
||||
droppedCopySynced = &filer_pb.RemoteEntry{StorageName: "s3", RemoteETag: `"abc"`, RemoteSize: 1024, RemoteMtime: droppedCopyMtime, LastLocalSyncTsNs: droppedCopyMtime*1e9 + 500}
|
||||
)
|
||||
|
||||
// droppedCopyStamp is the synced stamp with LastLocalSyncTsNs cleared, as
|
||||
// remote.uncache and the eviction leave it.
|
||||
func droppedCopyStamp() *filer_pb.RemoteEntry {
|
||||
stamp := proto.Clone(droppedCopySynced).(*filer_pb.RemoteEntry)
|
||||
stamp.LastLocalSyncTsNs = 0
|
||||
return stamp
|
||||
}
|
||||
|
||||
// droppedCopyEntry is the fixture file with the given stamp and chunks, sized
|
||||
// as its remote object.
|
||||
func droppedCopyEntry(stamp *filer_pb.RemoteEntry, chunks ...*filer_pb.FileChunk) *filer_pb.Entry {
|
||||
entry := entryWith(droppedCopyName, stamp, chunks...)
|
||||
entry.Attributes.FileSize = uint64(droppedCopySynced.RemoteSize)
|
||||
return entry
|
||||
}
|
||||
|
||||
func droppedCopyUpdate(oldEntry, newEntry *filer_pb.Entry) *filer_pb.SubscribeMetadataResponse {
|
||||
return &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: droppedCopyDir,
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: oldEntry, NewParentPath: droppedCopyDir, NewEntry: newEntry},
|
||||
}
|
||||
}
|
||||
|
||||
// TestDroppedLocalCopyIsNotUploaded: remote.uncache and the filer's eviction
|
||||
// under storage pressure drop a synced entry's chunks and clear its sync
|
||||
// stamp; remote.meta.sync does the same when it pulls a newer remote version.
|
||||
// With the remote mtime in the entry's second, shouldSendToRemote falls back
|
||||
// to the cleared stamp and reads the entry as dirty. The object at the same
|
||||
// key is the entry's only content, so uploading the chunkless entry would
|
||||
// replace it with a zero-byte object. The update is skipped, and the stamp
|
||||
// stays cleared so remote.cache and eviction still see the entry as uncached.
|
||||
func TestDroppedLocalCopyIsNotUploaded(t *testing.T) {
|
||||
// the eviction's entry, built the way uncacheRemoteEntry builds it, and
|
||||
// the event the way the filer's CreateEntry emits it
|
||||
cached := &filer.Entry{
|
||||
FullPath: util.NewFullPath(droppedCopyDir, droppedCopyName),
|
||||
Attr: filer.Attr{Mtime: time.Unix(droppedCopyMtime, 0), Mode: 0660, FileSize: 1024},
|
||||
Chunks: []*filer_pb.FileChunk{chunk("3,01", "e1")},
|
||||
Remote: droppedCopySynced,
|
||||
}
|
||||
evicted := cached.ShallowClone()
|
||||
evicted.Chunks = nil
|
||||
evicted.Remote = proto.Clone(cached.Remote).(*filer_pb.RemoteEntry)
|
||||
evicted.Remote.LastLocalSyncTsNs = 0
|
||||
|
||||
// remote.meta.sync found a newer object: its mtime becomes the entry's
|
||||
newer := &filer_pb.RemoteEntry{StorageName: "s3", RemoteETag: `"def"`, RemoteSize: 4096, RemoteMtime: droppedCopyMtime + 60}
|
||||
pulled := &filer_pb.Entry{Name: droppedCopyName, Attributes: &filer_pb.FuseAttributes{Mtime: droppedCopyMtime + 60, FileSize: 4096}, RemoteEntry: newer}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
oldEntry *filer_pb.Entry
|
||||
newEntry *filer_pb.Entry
|
||||
}{
|
||||
{name: "remote.uncache", oldEntry: droppedCopyEntry(droppedCopySynced, chunk("3,01", "e1")), newEntry: droppedCopyEntry(droppedCopyStamp())},
|
||||
{name: "eviction under storage pressure", oldEntry: cached.ToProtoEntry(), newEntry: evicted.ToProtoEntry()},
|
||||
{name: "remote.meta.sync pulls a newer version", oldEntry: entryWith(droppedCopyName, droppedCopySynced, chunk("3,01", "e1")), newEntry: pulled},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
resp := droppedCopyUpdate(tt.oldEntry, tt.newEntry)
|
||||
if !shouldSendToRemote(tt.newEntry) {
|
||||
t.Fatal("precondition: the cleared stamp in the remote mtime's second reads as dirty, the bug's trigger")
|
||||
}
|
||||
if isMetadataOnlyUpdate(resp.Directory, resp.EventNotification) {
|
||||
t.Fatal("precondition: the dropped chunks make the update a content change")
|
||||
}
|
||||
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: tt.newEntry}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, "/buckets/gold", droppedCopyMount, resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none: the remote object is the entry's content and an upload would zero it", remote.writes)
|
||||
}
|
||||
if len(remote.deletes) != 0 || len(remote.metadataUpdates) != 0 {
|
||||
t.Errorf("deletes = %+v, metadata updates = %+v, want the remote object left alone", remote.deletes, remote.metadataUpdates)
|
||||
}
|
||||
if filerClient.updates != 0 {
|
||||
t.Errorf("stamped the entry %d times, want 0: a stamp would mark the uncached entry as cached", filerClient.updates)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("a metadata edit of a remote-only entry still reaches the remote", func(t *testing.T) {
|
||||
tagged := droppedCopyEntry(droppedCopyStamp())
|
||||
tagged.Extended = map[string][]byte{"X-Amz-Tagging-tier": []byte("gold")}
|
||||
resp := droppedCopyUpdate(droppedCopyEntry(droppedCopyStamp()), tagged)
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: tagged}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, "/buckets/gold", droppedCopyMount, resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.metadataUpdates) != 1 || len(remote.writes) != 0 {
|
||||
t.Errorf("metadata updates = %+v, writes = %+v, want one metadata update and no upload", remote.metadataUpdates, remote.writes)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestSameSecondRewriteIsStillUploaded: a rewrite that lands in the remote
|
||||
// mtime's second holds local data, so the skip for dropped local copies does
|
||||
// not apply and it is uploaded and restamped (#11715).
|
||||
func TestSameSecondRewriteIsStillUploaded(t *testing.T) {
|
||||
stale := proto.Clone(droppedCopySynced).(*filer_pb.RemoteEntry)
|
||||
stale.LastLocalSyncTsNs = droppedCopyMtime*1e9 + 100
|
||||
rewrite := func(stamp *filer_pb.RemoteEntry) *filer_pb.Entry {
|
||||
entry := entryWith(droppedCopyName, stamp, chunk("4,02", "e2"))
|
||||
entry.Attributes.MtimeNs = 337
|
||||
return entry
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
oldEntry *filer_pb.Entry
|
||||
newEntry *filer_pb.Entry
|
||||
}{
|
||||
// Filer.UpdateEntry clears the stamp of a content change
|
||||
{name: "synced entry, stamp cleared by the filer", oldEntry: entryWith(droppedCopyName, droppedCopySynced, chunk("3,01", "e1")), newEntry: rewrite(droppedCopyStamp())},
|
||||
{name: "synced entry, stamp older than the rewrite", oldEntry: entryWith(droppedCopyName, stale, chunk("3,01", "e1")), newEntry: rewrite(stale)},
|
||||
{name: "uncached entry", oldEntry: entryWith(droppedCopyName, droppedCopyStamp()), newEntry: rewrite(droppedCopyStamp())},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if tt.newEntry.Attributes.Mtime != tt.newEntry.RemoteEntry.RemoteMtime {
|
||||
t.Fatal("precondition: the rewrite lands in the remote mtime's second")
|
||||
}
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: tt.newEntry}
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, "/buckets/gold", droppedCopyMount, droppedCopyUpdate(tt.oldEntry, tt.newEntry)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], droppedCopyDest) {
|
||||
t.Fatalf("writes = %+v, want the rewrite uploaded to %s", remote.writes, remote_storage.FormatLocation(droppedCopyDest))
|
||||
}
|
||||
if !slices.Equal(remote.writtenChunks[0], []string{"4,02"}) {
|
||||
t.Errorf("uploaded chunks %v, want the rewrite's [4,02]", remote.writtenChunks[0])
|
||||
}
|
||||
if filerClient.updates != 1 {
|
||||
t.Errorf("stamped the entry %d times, want 1 after the upload", filerClient.updates)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTruncateToZeroIsUploaded: a FUSE truncate of a cached file to zero
|
||||
// (truncateEntry, or SetAttr with size 0) drops the chunks and keeps the
|
||||
// sized RemoteEntry, so the entry looks remote-only. Its size is no longer
|
||||
// the remote object's, and the empty file has to replace the object.
|
||||
func TestTruncateToZeroIsUploaded(t *testing.T) {
|
||||
truncated := func(mtime int64, mtimeNs int32) *filer_pb.Entry {
|
||||
// the filer clears the stamp of a content change
|
||||
entry := entryWith(droppedCopyName, droppedCopyStamp())
|
||||
entry.Attributes.Mtime, entry.Attributes.MtimeNs = mtime, mtimeNs
|
||||
return entry
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
newEntry *filer_pb.Entry
|
||||
}{
|
||||
{name: "in a later second", newEntry: truncated(droppedCopyMtime+5, 0)},
|
||||
{name: "in the remote mtime's second", newEntry: truncated(droppedCopyMtime, 337)},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if !isRemoteOnly(tt.newEntry) {
|
||||
t.Fatal("precondition: the truncated entry looks remote-only")
|
||||
}
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: tt.newEntry}
|
||||
resp := droppedCopyUpdate(droppedCopyEntry(droppedCopySynced, chunk("3,01", "e1")), tt.newEntry)
|
||||
if err := processUpdateEvent(filerClient, filerClient, "", remote, "/buckets/gold", droppedCopyMount, resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], droppedCopyDest) {
|
||||
t.Fatalf("writes = %+v, want the empty file uploaded to %s", remote.writes, remote_storage.FormatLocation(droppedCopyDest))
|
||||
}
|
||||
if len(remote.writtenChunks[0]) != 0 {
|
||||
t.Errorf("uploaded chunks %v, want none: a zero-byte object", remote.writtenChunks[0])
|
||||
}
|
||||
if filerClient.updates != 1 {
|
||||
t.Errorf("stamped the entry %d times, want 1 after the upload", filerClient.updates)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteRemoteOnlyRenameKeepsAReusedOldKey(t *testing.T) {
|
||||
// A was renamed to B, then D to A before the sync got to the first
|
||||
// rename: the object at A is now D's, and the only copy of it
|
||||
|
||||
@@ -34,6 +34,14 @@ connection_max_lifetime_seconds = 3600
|
||||
[credential.memory]
|
||||
enabled = false
|
||||
|
||||
# Store secret keys KMS-encrypted instead of plaintext.
|
||||
# Requires a KMS provider configured in the [kms] section (filer.toml or
|
||||
# security.toml): local, aws, azure, gcp, or openbao for Vault/OpenBao.
|
||||
# Existing plaintext secrets keep working and are encrypted on their next write.
|
||||
[credential.encryption]
|
||||
enabled = false
|
||||
#key_id = "seaweedfs-credentials"
|
||||
|
||||
# Environment variable overrides:
|
||||
# Any configuration value can be overridden by environment variables
|
||||
# Rules:
|
||||
|
||||
@@ -101,6 +101,25 @@ connection_max_lifetime_seconds = 3600
|
||||
enabled = true
|
||||
```
|
||||
|
||||
### Encrypted Secret Keys
|
||||
|
||||
Any store can persist secret keys encrypted instead of plaintext:
|
||||
|
||||
```toml
|
||||
[credential.filer_etc]
|
||||
enabled = true
|
||||
|
||||
[credential.encryption]
|
||||
enabled = true
|
||||
#key_id = "seaweedfs-credentials" # optional KMS key id
|
||||
```
|
||||
|
||||
Secrets are wrapped with a data key from the configured KMS provider
|
||||
(`[kms]` section — local, aws, azure, gcp, or openbao for Vault/OpenBao),
|
||||
so the master key material can live in an external KMS or Vault. Secrets
|
||||
already stored in plaintext keep working and are encrypted on their next
|
||||
write.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
All credential configuration can be overridden with environment variables:
|
||||
|
||||
@@ -58,6 +58,11 @@ func NewCredentialManager(storeName CredentialStoreTypeName, configuration util.
|
||||
return nil, fmt.Errorf("failed to initialize credential store '%s': %v", storeName, err)
|
||||
}
|
||||
|
||||
if configuration != nil && configuration.GetBool("credential.encryption.enabled") {
|
||||
store = NewEncryptedCredentialStore(store, configuration.GetString("credential.encryption.key_id"))
|
||||
glog.V(0).Infof("Credential store '%s' persists secret keys KMS-encrypted", storeName)
|
||||
}
|
||||
|
||||
return &CredentialManager{
|
||||
Store: store,
|
||||
}, nil
|
||||
|
||||
@@ -0,0 +1,415 @@
|
||||
package credential
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/kms"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// CredentialEncryptionKeyID is the default KMS key used to wrap secret keys
|
||||
// when credential.toml enables encryption without naming one.
|
||||
const CredentialEncryptionKeyID = "seaweedfs-credentials"
|
||||
|
||||
// encryptedDataKeyField carries the KMS-wrapped data key inside the envelope.
|
||||
const encryptedDataKeyField = "encrypted_data_key"
|
||||
|
||||
// credentialEncryptionContext authenticates the data key wrapping so a blob
|
||||
// cannot be replayed from a different subsystem.
|
||||
var credentialEncryptionContext = map[string]string{"seaweedfs": "credential-store"}
|
||||
|
||||
// EncryptedCredentialStore wraps another credential store and encrypts secret
|
||||
// keys before they are persisted, decrypting them on reads. Secrets stored
|
||||
// without an envelope pass through unchanged, so existing plaintext
|
||||
// configurations keep working while new writes are encrypted.
|
||||
type EncryptedCredentialStore struct {
|
||||
CredentialStore
|
||||
keyID string
|
||||
}
|
||||
|
||||
var _ CredentialStore = &EncryptedCredentialStore{}
|
||||
|
||||
// NewEncryptedCredentialStore wraps an upstream store with secret encryption
|
||||
// under the named KMS key. An empty keyID uses CredentialEncryptionKeyID.
|
||||
func NewEncryptedCredentialStore(upstream CredentialStore, keyID string) CredentialStore {
|
||||
if keyID == "" {
|
||||
keyID = CredentialEncryptionKeyID
|
||||
}
|
||||
wrapped := &EncryptedCredentialStore{CredentialStore: upstream, keyID: keyID}
|
||||
if _, ok := upstream.(UserRenamer); ok {
|
||||
return &encryptedRenamerStore{wrapped}
|
||||
}
|
||||
return wrapped
|
||||
}
|
||||
|
||||
// encryptedRenamerStore adds RenameUser to the wrapper only when the upstream
|
||||
// store supports it, so wrapped stores keep their atomic rename capability.
|
||||
type encryptedRenamerStore struct {
|
||||
*EncryptedCredentialStore
|
||||
}
|
||||
|
||||
func (s *encryptedRenamerStore) RenameUser(ctx context.Context, oldName, newName string) error {
|
||||
return s.CredentialStore.(UserRenamer).RenameUser(ctx, oldName, newName)
|
||||
}
|
||||
|
||||
// SetFilerAddressFunc forwards a dynamic filer address to stores that need it.
|
||||
func (s *EncryptedCredentialStore) SetFilerAddressFunc(getFiler func() pb.ServerAddress, grpcDialOption grpc.DialOption) {
|
||||
if setter, ok := s.CredentialStore.(FilerAddressSetter); ok {
|
||||
setter.SetFilerAddressFunc(getFiler, grpcDialOption)
|
||||
}
|
||||
}
|
||||
|
||||
// The optional interface forwarders below return the same neutral results the
|
||||
// CredentialManager produces for stores without the capability, so wrapping a
|
||||
// store never changes which calls succeed.
|
||||
|
||||
func (s *EncryptedCredentialStore) PutUserInlinePolicy(ctx context.Context, userName, policyName string, document policy_engine.PolicyDocument) error {
|
||||
if store, ok := s.CredentialStore.(InlinePolicyStore); ok {
|
||||
return store.PutUserInlinePolicy(ctx, userName, policyName, document)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) GetUserInlinePolicy(ctx context.Context, userName, policyName string) (*policy_engine.PolicyDocument, error) {
|
||||
if store, ok := s.CredentialStore.(InlinePolicyStore); ok {
|
||||
return store.GetUserInlinePolicy(ctx, userName, policyName)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) DeleteUserInlinePolicy(ctx context.Context, userName, policyName string) error {
|
||||
if store, ok := s.CredentialStore.(InlinePolicyStore); ok {
|
||||
return store.DeleteUserInlinePolicy(ctx, userName, policyName)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) ListUserInlinePolicies(ctx context.Context, userName string) ([]string, error) {
|
||||
if store, ok := s.CredentialStore.(InlinePolicyStore); ok {
|
||||
return store.ListUserInlinePolicies(ctx, userName)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) LoadInlinePolicies(ctx context.Context) (map[string]map[string]policy_engine.PolicyDocument, error) {
|
||||
if loader, ok := s.CredentialStore.(InlinePoliciesLoader); ok {
|
||||
return loader.LoadInlinePolicies(ctx)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) PutGroupInlinePolicy(ctx context.Context, groupName, policyName string, document policy_engine.PolicyDocument) error {
|
||||
if store, ok := s.CredentialStore.(GroupInlinePolicyStore); ok {
|
||||
return store.PutGroupInlinePolicy(ctx, groupName, policyName, document)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) GetGroupInlinePolicy(ctx context.Context, groupName, policyName string) (*policy_engine.PolicyDocument, error) {
|
||||
if store, ok := s.CredentialStore.(GroupInlinePolicyStore); ok {
|
||||
return store.GetGroupInlinePolicy(ctx, groupName, policyName)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) DeleteGroupInlinePolicy(ctx context.Context, groupName, policyName string) error {
|
||||
if store, ok := s.CredentialStore.(GroupInlinePolicyStore); ok {
|
||||
return store.DeleteGroupInlinePolicy(ctx, groupName, policyName)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) ListGroupInlinePolicies(ctx context.Context, groupName string) ([]string, error) {
|
||||
if store, ok := s.CredentialStore.(GroupInlinePolicyStore); ok {
|
||||
return store.ListGroupInlinePolicies(ctx, groupName)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) LoadGroupInlinePolicies(ctx context.Context) (map[string]map[string]policy_engine.PolicyDocument, error) {
|
||||
if loader, ok := s.CredentialStore.(GroupInlinePoliciesLoader); ok {
|
||||
return loader.LoadGroupInlinePolicies(ctx)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) provider() (kms.KMSProvider, error) {
|
||||
provider := kms.GetGlobalKMS()
|
||||
if provider == nil {
|
||||
return nil, fmt.Errorf("credential encryption is enabled but no KMS provider is configured (see the [kms] section)")
|
||||
}
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) encryptSecret(ctx context.Context, plaintext string) (string, error) {
|
||||
if plaintext == "" {
|
||||
return plaintext, nil
|
||||
}
|
||||
if envelope, err := kms.ParseEnvelope([]byte(plaintext)); err == nil && envelope.ProviderSpecific[encryptedDataKeyField] != nil {
|
||||
return plaintext, nil
|
||||
}
|
||||
provider, err := s.provider()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
keyID, err := provider.GetKeyID(ctx, s.keyID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve credential encryption key: %w", err)
|
||||
}
|
||||
dataKey, err := provider.GenerateDataKey(ctx, &kms.GenerateDataKeyRequest{
|
||||
KeyID: keyID,
|
||||
KeySpec: kms.KeySpecAES256,
|
||||
EncryptionContext: credentialEncryptionContext,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("generate credential data key: %w", err)
|
||||
}
|
||||
defer kms.ClearSensitiveData(dataKey.Plaintext)
|
||||
|
||||
aesgcm, err := newGCM(dataKey.Plaintext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
nonce := make([]byte, aesgcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", err
|
||||
}
|
||||
blob := aesgcm.Seal(nonce, nonce, []byte(plaintext), []byte(keyID))
|
||||
|
||||
envelope, err := kms.CreateEnvelope("kms", keyID, base64.StdEncoding.EncodeToString(blob), map[string]interface{}{
|
||||
encryptedDataKeyField: base64.StdEncoding.EncodeToString(dataKey.CiphertextBlob),
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(envelope), nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) decryptSecret(ctx context.Context, stored string) (string, error) {
|
||||
envelope, err := kms.ParseEnvelope([]byte(stored))
|
||||
if err != nil {
|
||||
return stored, nil
|
||||
}
|
||||
blob, err := base64.StdEncoding.DecodeString(envelope.Ciphertext)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("decode credential ciphertext: %w", err)
|
||||
}
|
||||
encDataKey, ok := envelope.ProviderSpecific[encryptedDataKeyField].(string)
|
||||
if !ok || encDataKey == "" {
|
||||
return "", fmt.Errorf("credential envelope missing %s", encryptedDataKeyField)
|
||||
}
|
||||
encDataKeyBytes, err := base64.StdEncoding.DecodeString(encDataKey)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("decode credential data key: %w", err)
|
||||
}
|
||||
|
||||
provider, err := s.provider()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
dataKey, err := provider.Decrypt(ctx, &kms.DecryptRequest{
|
||||
CiphertextBlob: encDataKeyBytes,
|
||||
EncryptionContext: credentialEncryptionContext,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("decrypt credential data key: %w", err)
|
||||
}
|
||||
defer kms.ClearSensitiveData(dataKey.Plaintext)
|
||||
|
||||
aesgcm, err := newGCM(dataKey.Plaintext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(blob) < aesgcm.NonceSize() {
|
||||
return "", fmt.Errorf("credential ciphertext too short")
|
||||
}
|
||||
plain, err := aesgcm.Open(nil, blob[:aesgcm.NonceSize()], blob[aesgcm.NonceSize():], []byte(envelope.KeyID))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("decrypt credential secret: %w", err)
|
||||
}
|
||||
return string(plain), nil
|
||||
}
|
||||
|
||||
func newGCM(dataKey []byte) (cipher.AEAD, error) {
|
||||
block, err := aes.NewCipher(dataKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cipher.NewGCM(block)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) encryptIdentity(ctx context.Context, identity *iam_pb.Identity) (*iam_pb.Identity, error) {
|
||||
cloned := proto.Clone(identity).(*iam_pb.Identity)
|
||||
for _, cred := range cloned.Credentials {
|
||||
encrypted, err := s.encryptSecret(ctx, cred.SecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cred.SecretKey = encrypted
|
||||
}
|
||||
return cloned, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) decryptIdentity(ctx context.Context, identity *iam_pb.Identity) (*iam_pb.Identity, error) {
|
||||
if identity == nil {
|
||||
return nil, nil
|
||||
}
|
||||
for _, cred := range identity.Credentials {
|
||||
decrypted, err := s.decryptSecret(ctx, cred.SecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cred.SecretKey = decrypted
|
||||
}
|
||||
return identity, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) encryptServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) (*iam_pb.ServiceAccount, error) {
|
||||
cloned := proto.Clone(sa).(*iam_pb.ServiceAccount)
|
||||
if cloned.Credential != nil {
|
||||
encrypted, err := s.encryptSecret(ctx, cloned.Credential.SecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cloned.Credential.SecretKey = encrypted
|
||||
}
|
||||
return cloned, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) decryptServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) (*iam_pb.ServiceAccount, error) {
|
||||
if sa == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if sa.Credential != nil {
|
||||
decrypted, err := s.decryptSecret(ctx, sa.Credential.SecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sa.Credential.SecretKey = decrypted
|
||||
}
|
||||
return sa, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3ApiConfiguration, error) {
|
||||
config, err := s.CredentialStore.LoadConfiguration(ctx)
|
||||
if err != nil || config == nil {
|
||||
return config, err
|
||||
}
|
||||
for _, identity := range config.Identities {
|
||||
if _, err := s.decryptIdentity(ctx, identity); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) SaveConfiguration(ctx context.Context, config *iam_pb.S3ApiConfiguration) error {
|
||||
cloned := proto.Clone(config).(*iam_pb.S3ApiConfiguration)
|
||||
for _, identity := range cloned.Identities {
|
||||
for _, cred := range identity.Credentials {
|
||||
encrypted, err := s.encryptSecret(ctx, cred.SecretKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cred.SecretKey = encrypted
|
||||
}
|
||||
}
|
||||
return s.CredentialStore.SaveConfiguration(ctx, cloned)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) CreateUser(ctx context.Context, identity *iam_pb.Identity) error {
|
||||
encrypted, err := s.encryptIdentity(ctx, identity)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.CredentialStore.CreateUser(ctx, encrypted)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) GetUser(ctx context.Context, username string) (*iam_pb.Identity, error) {
|
||||
identity, err := s.CredentialStore.GetUser(ctx, username)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.decryptIdentity(ctx, identity)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) UpdateUser(ctx context.Context, username string, identity *iam_pb.Identity) error {
|
||||
encrypted, err := s.encryptIdentity(ctx, identity)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.CredentialStore.UpdateUser(ctx, username, encrypted)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) GetUserByAccessKey(ctx context.Context, accessKey string) (*iam_pb.Identity, error) {
|
||||
identity, err := s.CredentialStore.GetUserByAccessKey(ctx, accessKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.decryptIdentity(ctx, identity)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) CreateAccessKey(ctx context.Context, username string, cred *iam_pb.Credential) error {
|
||||
cloned := proto.Clone(cred).(*iam_pb.Credential)
|
||||
encrypted, err := s.encryptSecret(ctx, cloned.SecretKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cloned.SecretKey = encrypted
|
||||
return s.CredentialStore.CreateAccessKey(ctx, username, cloned)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) CreateServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) error {
|
||||
encrypted, err := s.encryptServiceAccount(ctx, sa)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.CredentialStore.CreateServiceAccount(ctx, encrypted)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) UpdateServiceAccount(ctx context.Context, id string, sa *iam_pb.ServiceAccount) error {
|
||||
encrypted, err := s.encryptServiceAccount(ctx, sa)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.CredentialStore.UpdateServiceAccount(ctx, id, encrypted)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) GetServiceAccount(ctx context.Context, id string) (*iam_pb.ServiceAccount, error) {
|
||||
sa, err := s.CredentialStore.GetServiceAccount(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.decryptServiceAccount(ctx, sa)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) ListServiceAccounts(ctx context.Context) ([]*iam_pb.ServiceAccount, error) {
|
||||
accounts, err := s.CredentialStore.ListServiceAccounts(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, sa := range accounts {
|
||||
if _, err := s.decryptServiceAccount(ctx, sa); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) GetServiceAccountByAccessKey(ctx context.Context, accessKey string) (*iam_pb.ServiceAccount, error) {
|
||||
sa, err := s.CredentialStore.GetServiceAccountByAccessKey(ctx, accessKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.decryptServiceAccount(ctx, sa)
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package credential
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/kms"
|
||||
"github.com/seaweedfs/seaweedfs/weed/kms/local"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// fakeStore is a minimal in-memory CredentialStore for exercising the
|
||||
// encryption wrapper; unneeded methods panic via the embedded nil interface.
|
||||
type fakeStore struct {
|
||||
CredentialStore
|
||||
config *iam_pb.S3ApiConfiguration
|
||||
users map[string]*iam_pb.Identity
|
||||
sas map[string]*iam_pb.ServiceAccount
|
||||
}
|
||||
|
||||
func newFakeStore() *fakeStore {
|
||||
return &fakeStore{users: map[string]*iam_pb.Identity{}, sas: map[string]*iam_pb.ServiceAccount{}}
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetName() CredentialStoreTypeName { return "fake" }
|
||||
|
||||
func (f *fakeStore) CreateUser(ctx context.Context, identity *iam_pb.Identity) error {
|
||||
f.users[identity.Name] = proto.Clone(identity).(*iam_pb.Identity)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetUser(ctx context.Context, username string) (*iam_pb.Identity, error) {
|
||||
if u, ok := f.users[username]; ok {
|
||||
return proto.Clone(u).(*iam_pb.Identity), nil
|
||||
}
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
|
||||
func (f *fakeStore) UpdateUser(ctx context.Context, username string, identity *iam_pb.Identity) error {
|
||||
return f.CreateUser(ctx, identity)
|
||||
}
|
||||
|
||||
func (f *fakeStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3ApiConfiguration, error) {
|
||||
return proto.Clone(f.config).(*iam_pb.S3ApiConfiguration), nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) SaveConfiguration(ctx context.Context, config *iam_pb.S3ApiConfiguration) error {
|
||||
f.config = proto.Clone(config).(*iam_pb.S3ApiConfiguration)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) CreateAccessKey(ctx context.Context, username string, cred *iam_pb.Credential) error {
|
||||
f.users[username].Credentials = append(f.users[username].Credentials, proto.Clone(cred).(*iam_pb.Credential))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) CreateServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) error {
|
||||
f.sas[sa.Id] = proto.Clone(sa).(*iam_pb.ServiceAccount)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetServiceAccount(ctx context.Context, id string) (*iam_pb.ServiceAccount, error) {
|
||||
return proto.Clone(f.sas[id]).(*iam_pb.ServiceAccount), nil
|
||||
}
|
||||
|
||||
func setupKMS(t *testing.T) {
|
||||
t.Helper()
|
||||
provider, err := local.NewLocalKMSProvider(nil)
|
||||
require.NoError(t, err)
|
||||
kms.SetGlobalKMSProvider(provider)
|
||||
t.Cleanup(func() { kms.SetGlobalKMSProvider(nil) })
|
||||
}
|
||||
|
||||
func testIdentity() *iam_pb.Identity {
|
||||
return &iam_pb.Identity{
|
||||
Name: "alice",
|
||||
Credentials: []*iam_pb.Credential{
|
||||
{AccessKey: "AKIA_TEST", SecretKey: "secret-one"},
|
||||
},
|
||||
Actions: []string{"Read"},
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncryptedStoreRoundTrip(t *testing.T) {
|
||||
setupKMS(t)
|
||||
fake := newFakeStore()
|
||||
store := NewEncryptedCredentialStore(fake, "")
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, store.CreateUser(ctx, testIdentity()))
|
||||
|
||||
stored := fake.users["alice"].Credentials[0].SecretKey
|
||||
assert.NotEqual(t, "secret-one", stored)
|
||||
assert.True(t, strings.HasPrefix(stored, "{"), "stored secret should be an envelope: %s", stored)
|
||||
envelope, err := kms.ParseEnvelope([]byte(stored))
|
||||
require.NoError(t, err)
|
||||
assert.NotEmpty(t, envelope.Ciphertext)
|
||||
assert.NotEmpty(t, envelope.ProviderSpecific[encryptedDataKeyField])
|
||||
|
||||
got, err := store.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "secret-one", got.Credentials[0].SecretKey)
|
||||
assert.Equal(t, "AKIA_TEST", got.Credentials[0].AccessKey)
|
||||
}
|
||||
|
||||
func TestEncryptedStorePlaintextPassthrough(t *testing.T) {
|
||||
fake := newFakeStore()
|
||||
fake.users["bob"] = testIdentity()
|
||||
fake.users["bob"].Name = "bob"
|
||||
store := NewEncryptedCredentialStore(fake, "")
|
||||
|
||||
got, err := store.GetUser(context.Background(), "bob")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "secret-one", got.Credentials[0].SecretKey)
|
||||
}
|
||||
|
||||
func TestEncryptedStoreNoKMSFailsWrite(t *testing.T) {
|
||||
kms.SetGlobalKMSProvider(nil)
|
||||
fake := newFakeStore()
|
||||
store := NewEncryptedCredentialStore(fake, "")
|
||||
|
||||
err := store.CreateUser(context.Background(), testIdentity())
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "KMS provider")
|
||||
assert.Empty(t, fake.users, "failed writes must not persist plaintext secrets")
|
||||
}
|
||||
|
||||
func TestEncryptedStoreSaveLoadConfiguration(t *testing.T) {
|
||||
setupKMS(t)
|
||||
fake := newFakeStore()
|
||||
store := NewEncryptedCredentialStore(fake, "")
|
||||
ctx := context.Background()
|
||||
|
||||
config := &iam_pb.S3ApiConfiguration{Identities: []*iam_pb.Identity{testIdentity()}}
|
||||
require.NoError(t, store.SaveConfiguration(ctx, config))
|
||||
assert.Equal(t, "secret-one", config.Identities[0].Credentials[0].SecretKey,
|
||||
"the caller's config object must not be mutated")
|
||||
|
||||
loaded, err := store.LoadConfiguration(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "secret-one", loaded.Identities[0].Credentials[0].SecretKey)
|
||||
|
||||
stored := fake.config.Identities[0].Credentials[0].SecretKey
|
||||
assert.NotEqual(t, "secret-one", stored)
|
||||
}
|
||||
|
||||
func TestEncryptedStoreServiceAccount(t *testing.T) {
|
||||
setupKMS(t)
|
||||
fake := newFakeStore()
|
||||
store := NewEncryptedCredentialStore(fake, "")
|
||||
ctx := context.Background()
|
||||
|
||||
sa := &iam_pb.ServiceAccount{
|
||||
Id: "sa-1",
|
||||
ParentUser: "alice",
|
||||
Credential: &iam_pb.Credential{AccessKey: "SA_KEY", SecretKey: "sa-secret"},
|
||||
}
|
||||
require.NoError(t, store.CreateServiceAccount(ctx, sa))
|
||||
|
||||
assert.NotEqual(t, "sa-secret", fake.sas["sa-1"].Credential.SecretKey)
|
||||
|
||||
got, err := store.GetServiceAccount(ctx, "sa-1")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "sa-secret", got.Credential.SecretKey)
|
||||
}
|
||||
|
||||
func TestEncryptedStoreNoDoubleWrap(t *testing.T) {
|
||||
setupKMS(t)
|
||||
fake := newFakeStore()
|
||||
store := NewEncryptedCredentialStore(fake, "")
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, store.CreateUser(ctx, testIdentity()))
|
||||
storedOnce := fake.users["alice"].Credentials[0].SecretKey
|
||||
|
||||
// Saving an already-enveloped value must not wrap it again.
|
||||
identity := testIdentity()
|
||||
identity.Credentials[0].SecretKey = storedOnce
|
||||
require.NoError(t, store.UpdateUser(ctx, "alice", identity))
|
||||
assert.Equal(t, storedOnce, fake.users["alice"].Credentials[0].SecretKey)
|
||||
|
||||
got, err := store.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "secret-one", got.Credentials[0].SecretKey)
|
||||
}
|
||||
@@ -2,10 +2,16 @@ package iamapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -141,3 +147,69 @@ func TestIamManagementAllowedForAdmin(t *testing.T) {
|
||||
"", "Action=CreateUser&UserName=new-user&Version=2010-05-08")
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
}
|
||||
|
||||
// The implicit UserName must come from the identity authentication verified,
|
||||
// never from re-parsing the Authorization header: a request can carry presigned
|
||||
// credentials for one user alongside a junk SigV4 header naming another.
|
||||
func TestImplicitUserNameUsesVerifiedIdentity(t *testing.T) {
|
||||
server := newAuthzTestServer(t)
|
||||
expires := strconv.FormatInt(time.Now().Add(10*time.Minute).Unix(), 10)
|
||||
sts := "POST\n\napplication/x-www-form-urlencoded\n" + expires + "\n/"
|
||||
mac := hmac.New(sha1.New, []byte("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"))
|
||||
mac.Write([]byte(sts))
|
||||
sig := base64.StdEncoding.EncodeToString(mac.Sum(nil))
|
||||
q := url.Values{"AWSAccessKeyId": {"AKIAIOSFODNN7EXAMPLE"}, "Expires": {expires}, "Signature": {sig}}
|
||||
|
||||
post := func(t *testing.T, body string) (int, string) {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodPost, server.URL+"/?"+q.Encode(), strings.NewReader(body))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential=AKIATESTFAKEADMIN0001/20261021/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=00")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
t.Logf("%d %s", resp.StatusCode, b)
|
||||
return resp.StatusCode, string(b)
|
||||
}
|
||||
|
||||
for _, action := range []string{"ListAccessKeys", "CreateAccessKey", "GetUser"} {
|
||||
t.Run(action, func(t *testing.T) {
|
||||
code, body := post(t, "Action="+action+"&Version=2010-05-08")
|
||||
assert.Equal(t, http.StatusOK, code)
|
||||
assert.NotContains(t, body, "iam_admin")
|
||||
assert.Contains(t, body, "power_user")
|
||||
})
|
||||
}
|
||||
|
||||
// ListUserPolicies is not self-service: a caller without IAM rights is
|
||||
// denied whichever name the implicit resolution lands on.
|
||||
t.Run("ListUserPolicies", func(t *testing.T) {
|
||||
code, body := post(t, "Action=ListUserPolicies&Version=2010-05-08")
|
||||
assert.Equal(t, http.StatusForbidden, code)
|
||||
assert.NotContains(t, body, "iam_admin")
|
||||
})
|
||||
|
||||
// A write aimed at the header-named admin's key resolves to the verified
|
||||
// caller instead: the key is not power_user's, so it is not found.
|
||||
t.Run("UpdateAccessKey", func(t *testing.T) {
|
||||
code, body := post(t, "Action=UpdateAccessKey&AccessKeyId=AKIATESTFAKEADMIN0001&Status=Inactive&Version=2010-05-08")
|
||||
assert.Equal(t, http.StatusNotFound, code)
|
||||
assert.Contains(t, body, "NoSuchEntity")
|
||||
})
|
||||
|
||||
t.Run("DeleteAccessKey", func(t *testing.T) {
|
||||
code, _ := post(t, "Action=DeleteAccessKey&AccessKeyId=AKIATESTFAKEADMIN0001&Version=2010-05-08")
|
||||
assert.Equal(t, http.StatusOK, code)
|
||||
})
|
||||
|
||||
// The admin key the junk header named is untouched: still present and active.
|
||||
resp := postSignedIamAction(t, server.URL, "AKIATESTFAKEADMIN0001", "testAdminSecretFake0000000000000000000000",
|
||||
"", "Action=ListAccessKeys&Version=2010-05-08")
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(body), "AKIATESTFAKEADMIN0001")
|
||||
assert.Contains(t, string(body), "<Status>Active</Status>")
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/request_id"
|
||||
)
|
||||
@@ -1265,53 +1266,19 @@ func (iama *IamApiServer) DeleteAccessKey(s3cfg *iam_pb.S3ApiConfiguration, valu
|
||||
return resp
|
||||
}
|
||||
|
||||
// handleImplicitUsername adds username who signs the request to values if 'username' is not specified.
|
||||
// According to AWS documentation: "If you do not specify a user name, IAM determines the user name
|
||||
// implicitly based on the Amazon Web Services access key ID signing the request."
|
||||
// This function extracts the AccessKeyId from the SigV4 credential and looks up the corresponding
|
||||
// identity name in the credential store.
|
||||
// handleImplicitUsername adds the name of the authenticated caller to values
|
||||
// when 'UserName' is not specified, per AWS: "If you do not specify a user name,
|
||||
// IAM determines the user name implicitly based on the Amazon Web Services
|
||||
// access key ID signing the request." The name comes from the identity the
|
||||
// authentication middleware verified, which the request context carries; the
|
||||
// Authorization header itself is attacker-controlled and is never re-parsed.
|
||||
func (iama *IamApiServer) handleImplicitUsername(r *http.Request, values url.Values) {
|
||||
if len(r.Header["Authorization"]) == 0 || values.Get("UserName") != "" {
|
||||
if values.Get("UserName") != "" {
|
||||
return
|
||||
}
|
||||
// Log presence of auth header without exposing sensitive signature material
|
||||
glog.V(4).Infof("Authorization header present, extracting access key")
|
||||
// Parse AWS SigV4 Authorization header format:
|
||||
// "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/iam/aws4_request, ..."
|
||||
s := strings.Split(r.Header["Authorization"][0], "Credential=")
|
||||
if len(s) < 2 {
|
||||
return
|
||||
if name := s3_constants.GetIdentityNameFromContext(r); name != "" {
|
||||
values.Set("UserName", name)
|
||||
}
|
||||
s = strings.Split(s[1], ",")
|
||||
if len(s) < 1 {
|
||||
return
|
||||
}
|
||||
s = strings.Split(s[0], "/")
|
||||
if len(s) < 1 {
|
||||
return
|
||||
}
|
||||
// s[0] is the AccessKeyId
|
||||
accessKeyId := s[0]
|
||||
if accessKeyId == "" {
|
||||
return
|
||||
}
|
||||
// Nil-guard: ensure iam is initialized before lookup
|
||||
if iama.iam == nil {
|
||||
glog.V(4).Infof("IAM not initialized, cannot look up access key")
|
||||
return
|
||||
}
|
||||
// Look up the identity by access key to get the username
|
||||
identity, _, found := iama.iam.LookupByAccessKey(accessKeyId)
|
||||
if !found {
|
||||
// Mask access key in logs - show only first 4 chars
|
||||
maskedKey := accessKeyId
|
||||
if len(accessKeyId) > 4 {
|
||||
maskedKey = accessKeyId[:4] + "***"
|
||||
}
|
||||
glog.V(4).Infof("Access key %s not found in credential store", maskedKey)
|
||||
return
|
||||
}
|
||||
values.Set("UserName", identity.Name)
|
||||
}
|
||||
|
||||
// targetedCredentialManager returns the credential manager through which a change to the named
|
||||
@@ -1470,6 +1437,7 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
case "GetUser":
|
||||
iama.handleImplicitUsername(r, values)
|
||||
userName := values.Get("UserName")
|
||||
var err *IamError
|
||||
response, err = iama.GetUser(s3cfg, userName)
|
||||
|
||||
+14
-32
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/request_id"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -524,32 +525,13 @@ func executeRequest(req *http.Request, v interface{}) (*httptest.ResponseRecorde
|
||||
}
|
||||
|
||||
func TestHandleImplicitUsername(t *testing.T) {
|
||||
// Create a mock IamApiServer with credential store
|
||||
// The handleImplicitUsername function now looks up the username from the
|
||||
// credential store based on AccessKeyId, not from the region field in the auth header.
|
||||
// Note: Using obviously fake access keys to avoid CI secret scanner false positives
|
||||
// The implicit name is the authenticated identity recorded in the request
|
||||
// context by the auth middleware; request headers are never re-parsed.
|
||||
iama := &IamApiServer{}
|
||||
|
||||
// Create IAM directly as struct literal (same pattern as other tests)
|
||||
iam := &s3api.IdentityAccessManagement{}
|
||||
|
||||
// Load test credentials - map access key to identity name
|
||||
testConfig := &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{
|
||||
Name: "testuser1",
|
||||
Credentials: []*iam_pb.Credential{
|
||||
{AccessKey: "AKIATESTFAKEKEY000001", SecretKey: "testsecretfake"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
err := iam.LoadS3ApiConfigurationFromBytes(mustMarshalJSON(t, testConfig))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to load test config: %v", err)
|
||||
}
|
||||
|
||||
iama := &IamApiServer{
|
||||
iam: iam,
|
||||
withIdentity := func(name string) *http.Request {
|
||||
r := &http.Request{Header: http.Header{}}
|
||||
return r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), name))
|
||||
}
|
||||
|
||||
var tests = []struct {
|
||||
@@ -557,14 +539,14 @@ func TestHandleImplicitUsername(t *testing.T) {
|
||||
values url.Values
|
||||
userName string
|
||||
}{
|
||||
// No authorization header - should not set username
|
||||
// No authenticated identity - should not set username
|
||||
{&http.Request{}, url.Values{}, ""},
|
||||
// Valid auth header with known access key - should look up and find "testuser1"
|
||||
{&http.Request{Header: http.Header{"Authorization": []string{"AWS4-HMAC-SHA256 Credential=AKIATESTFAKEKEY000001/20220420/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=fakesignature0123456789abcdef"}}}, url.Values{}, "testuser1"},
|
||||
// Malformed auth header (no Credential=) - should not set username
|
||||
{&http.Request{Header: http.Header{"Authorization": []string{"AWS4-HMAC-SHA256 =AKIATESTFAKEKEY000001/20220420/test1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=fakesignature0123456789abcdef"}}}, url.Values{}, ""},
|
||||
// Unknown access key - should not set username
|
||||
{&http.Request{Header: http.Header{"Authorization": []string{"AWS4-HMAC-SHA256 Credential=AKIATESTUNKNOWN000000/20220420/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=fakesignature0123456789abcdef"}}}, url.Values{}, ""},
|
||||
// Authenticated identity in context - sets its name
|
||||
{withIdentity("testuser1"), url.Values{}, "testuser1"},
|
||||
// A client-controlled Authorization header naming another user is ignored
|
||||
{&http.Request{Header: http.Header{"Authorization": []string{"AWS4-HMAC-SHA256 Credential=AKIATESTFAKEKEY000001/20220420/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=fakesignature0123456789abcdef"}}}, url.Values{}, ""},
|
||||
// An explicit UserName is left alone
|
||||
{withIdentity("testuser1"), url.Values{"UserName": {"other"}}, "other"},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
|
||||
+47
-3
@@ -235,13 +235,15 @@ func buildPreflightResponse(rule *CORSRule, corsReq *CORSRequest) *CORSResponse
|
||||
|
||||
// Set exposed headers
|
||||
if len(rule.ExposeHeaders) > 0 {
|
||||
response.ExposeHeaders = strings.Join(rule.ExposeHeaders, ", ")
|
||||
response.ExposeHeaders = formatExposeHeaders(rule.ExposeHeaders)
|
||||
}
|
||||
|
||||
// Set max age
|
||||
if rule.MaxAgeSeconds != nil {
|
||||
response.MaxAge = strconv.Itoa(*rule.MaxAgeSeconds)
|
||||
}
|
||||
|
||||
response.AllowCredentials = true
|
||||
}
|
||||
|
||||
return response
|
||||
@@ -250,7 +252,8 @@ func buildPreflightResponse(rule *CORSRule, corsReq *CORSRequest) *CORSResponse
|
||||
// buildResponse builds a CORS response from a matching rule
|
||||
func buildResponse(rule *CORSRule, corsReq *CORSRequest) *CORSResponse {
|
||||
response := &CORSResponse{
|
||||
AllowOrigin: corsReq.Origin,
|
||||
AllowOrigin: corsReq.Origin,
|
||||
AllowCredentials: true,
|
||||
}
|
||||
|
||||
// Set allowed methods
|
||||
@@ -263,7 +266,7 @@ func buildResponse(rule *CORSRule, corsReq *CORSRequest) *CORSResponse {
|
||||
|
||||
// Set expose headers
|
||||
if len(rule.ExposeHeaders) > 0 {
|
||||
response.ExposeHeaders = strings.Join(rule.ExposeHeaders, ", ")
|
||||
response.ExposeHeaders = formatExposeHeaders(rule.ExposeHeaders)
|
||||
}
|
||||
|
||||
// Set max age
|
||||
@@ -274,6 +277,47 @@ func buildResponse(rule *CORSRule, corsReq *CORSRequest) *CORSResponse {
|
||||
return response
|
||||
}
|
||||
|
||||
// defaultExposeHeaders are emitted alongside "*" so credentialed CORS requests
|
||||
// can read standard response headers ("*" is treated literally when credentials
|
||||
// are included, per the Fetch spec).
|
||||
var defaultExposeHeaders = []string{
|
||||
"ETag",
|
||||
"Content-Length",
|
||||
"Content-Type",
|
||||
"Last-Modified",
|
||||
"Content-Range",
|
||||
"x-amz-request-id",
|
||||
"x-amz-version-id",
|
||||
"x-amz-tagging-count",
|
||||
}
|
||||
|
||||
// formatExposeHeaders formats the exposed headers slice into a comma-separated string.
|
||||
func formatExposeHeaders(exposeHeaders []string) string {
|
||||
var headers []string
|
||||
hasWildcard := false
|
||||
seen := map[string]bool{}
|
||||
for _, h := range exposeHeaders {
|
||||
if h == "*" {
|
||||
hasWildcard = true
|
||||
continue
|
||||
}
|
||||
if lower := strings.ToLower(h); !seen[lower] {
|
||||
seen[lower] = true
|
||||
headers = append(headers, h)
|
||||
}
|
||||
}
|
||||
if hasWildcard {
|
||||
for _, h := range defaultExposeHeaders {
|
||||
if lower := strings.ToLower(h); !seen[lower] {
|
||||
seen[lower] = true
|
||||
headers = append(headers, h)
|
||||
}
|
||||
}
|
||||
headers = append(headers, "*")
|
||||
}
|
||||
return strings.Join(headers, ", ")
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
|
||||
// matchesOrigin checks if the request origin matches any allowed origin
|
||||
|
||||
@@ -405,11 +405,12 @@ func TestEvaluateRequest(t *testing.T) {
|
||||
Method: "GET",
|
||||
},
|
||||
want: &CORSResponse{
|
||||
AllowOrigin: "http://example.com",
|
||||
AllowMethods: "GET, POST",
|
||||
AllowHeaders: "Content-Type",
|
||||
ExposeHeaders: "ETag",
|
||||
MaxAge: "3600",
|
||||
AllowOrigin: "http://example.com",
|
||||
AllowMethods: "GET, POST",
|
||||
AllowHeaders: "Content-Type",
|
||||
ExposeHeaders: "ETag",
|
||||
MaxAge: "3600",
|
||||
AllowCredentials: true,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
@@ -421,8 +422,9 @@ func TestEvaluateRequest(t *testing.T) {
|
||||
Method: "PUT",
|
||||
},
|
||||
want: &CORSResponse{
|
||||
AllowOrigin: "http://other.com",
|
||||
AllowMethods: "PUT",
|
||||
AllowOrigin: "http://other.com",
|
||||
AllowMethods: "PUT",
|
||||
AllowCredentials: true,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
@@ -447,11 +449,12 @@ func TestEvaluateRequest(t *testing.T) {
|
||||
AccessControlRequestHeaders: []string{"Content-Type"},
|
||||
},
|
||||
want: &CORSResponse{
|
||||
AllowOrigin: "http://example.com",
|
||||
AllowMethods: "GET, POST",
|
||||
AllowHeaders: "Content-Type",
|
||||
ExposeHeaders: "ETag",
|
||||
MaxAge: "3600",
|
||||
AllowOrigin: "http://example.com",
|
||||
AllowMethods: "GET, POST",
|
||||
AllowHeaders: "Content-Type",
|
||||
ExposeHeaders: "ETag",
|
||||
MaxAge: "3600",
|
||||
AllowCredentials: true,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
@@ -467,7 +470,30 @@ func TestEvaluateRequest(t *testing.T) {
|
||||
},
|
||||
want: &CORSResponse{
|
||||
AllowOrigin: "http://example.com",
|
||||
// No AllowMethods or AllowHeaders because the requested header is forbidden
|
||||
// No AllowMethods, AllowHeaders, or AllowCredentials because the requested header is forbidden
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "wildcard expose headers expands for credentialed responses",
|
||||
config: &CORSConfiguration{
|
||||
CORSRules: []CORSRule{
|
||||
{
|
||||
AllowedOrigins: []string{"http://example.com"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
ExposeHeaders: []string{"*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
corsReq: &CORSRequest{
|
||||
Origin: "http://example.com",
|
||||
Method: "GET",
|
||||
},
|
||||
want: &CORSResponse{
|
||||
AllowOrigin: "http://example.com",
|
||||
AllowMethods: "GET",
|
||||
ExposeHeaders: "ETag, Content-Length, Content-Type, Last-Modified, Content-Range, x-amz-request-id, x-amz-version-id, x-amz-tagging-count, *",
|
||||
AllowCredentials: true,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
@@ -511,18 +537,20 @@ func TestApplyHeaders(t *testing.T) {
|
||||
{
|
||||
name: "complete response",
|
||||
corsResp: &CORSResponse{
|
||||
AllowOrigin: "http://example.com",
|
||||
AllowMethods: "GET, POST",
|
||||
AllowHeaders: "Content-Type",
|
||||
ExposeHeaders: "ETag",
|
||||
MaxAge: "3600",
|
||||
AllowOrigin: "http://example.com",
|
||||
AllowMethods: "GET, POST",
|
||||
AllowHeaders: "Content-Type",
|
||||
ExposeHeaders: "ETag",
|
||||
MaxAge: "3600",
|
||||
AllowCredentials: true,
|
||||
},
|
||||
want: map[string]string{
|
||||
"Access-Control-Allow-Origin": "http://example.com",
|
||||
"Access-Control-Allow-Methods": "GET, POST",
|
||||
"Access-Control-Allow-Headers": "Content-Type",
|
||||
"Access-Control-Expose-Headers": "ETag",
|
||||
"Access-Control-Max-Age": "3600",
|
||||
"Access-Control-Allow-Origin": "http://example.com",
|
||||
"Access-Control-Allow-Methods": "GET, POST",
|
||||
"Access-Control-Allow-Headers": "Content-Type",
|
||||
"Access-Control-Expose-Headers": "ETag",
|
||||
"Access-Control-Max-Age": "3600",
|
||||
"Access-Control-Allow-Credentials": "true",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -2594,53 +2594,19 @@ func (e *EmbeddedIamApi) ListGroupPolicies(s3cfg *iam_pb.S3ApiConfiguration, val
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// handleImplicitUsername adds username who signs the request to values if 'username' is not specified.
|
||||
// According to AWS documentation: "If you do not specify a user name, IAM determines the user name
|
||||
// implicitly based on the Amazon Web Services access key ID signing the request."
|
||||
// This function extracts the AccessKeyId from the SigV4 credential and looks up the corresponding
|
||||
// identity name in the credential store.
|
||||
// handleImplicitUsername adds the name of the authenticated caller to values
|
||||
// when 'UserName' is not specified, per AWS: "If you do not specify a user name,
|
||||
// IAM determines the user name implicitly based on the Amazon Web Services
|
||||
// access key ID signing the request." The name comes from the identity the
|
||||
// authentication middleware verified, which the request context carries; the
|
||||
// Authorization header itself is attacker-controlled and is never re-parsed.
|
||||
func (e *EmbeddedIamApi) handleImplicitUsername(r *http.Request, values url.Values) {
|
||||
if len(r.Header["Authorization"]) == 0 || values.Get("UserName") != "" {
|
||||
if values.Get("UserName") != "" {
|
||||
return
|
||||
}
|
||||
// Log presence of auth header without exposing sensitive signature material
|
||||
glog.V(4).Infof("Authorization header present, extracting access key")
|
||||
// Parse AWS SigV4 Authorization header format:
|
||||
// "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/iam/aws4_request, ..."
|
||||
s := strings.Split(r.Header["Authorization"][0], "Credential=")
|
||||
if len(s) < 2 {
|
||||
return
|
||||
if name := s3_constants.GetIdentityNameFromContext(r); name != "" {
|
||||
values.Set("UserName", name)
|
||||
}
|
||||
s = strings.Split(s[1], ",")
|
||||
if len(s) < 1 {
|
||||
return
|
||||
}
|
||||
s = strings.Split(s[0], "/")
|
||||
if len(s) < 1 {
|
||||
return
|
||||
}
|
||||
// s[0] is the AccessKeyId
|
||||
accessKeyId := s[0]
|
||||
if accessKeyId == "" {
|
||||
return
|
||||
}
|
||||
// Nil-guard: ensure iam is initialized before lookup
|
||||
if e.iam == nil {
|
||||
glog.V(4).Infof("IAM not initialized, cannot look up access key")
|
||||
return
|
||||
}
|
||||
// Look up the identity by access key to get the username
|
||||
identity, _, found := e.iam.LookupByAccessKey(accessKeyId)
|
||||
if !found {
|
||||
// Mask access key in logs - show only first 4 chars
|
||||
maskedKey := accessKeyId
|
||||
if len(accessKeyId) > 4 {
|
||||
maskedKey = accessKeyId[:4] + "***"
|
||||
}
|
||||
glog.V(4).Infof("Access key %s not found in credential store", maskedKey)
|
||||
return
|
||||
}
|
||||
values.Set("UserName", identity.Name)
|
||||
}
|
||||
|
||||
// iamSelfServiceActions are actions that users can perform on their own resources without admin rights.
|
||||
|
||||
@@ -372,13 +372,13 @@ func TestEmbeddedIamGetUserImplicitUsername(t *testing.T) {
|
||||
t.Fatalf("failed to load iam config: %v", err)
|
||||
}
|
||||
|
||||
// GetUser request with NO UserName, but signed by accessKey.
|
||||
// GetUser request with NO UserName, carrying the identity authentication
|
||||
// verified for accessKey, the way the middleware records it.
|
||||
form := url.Values{}
|
||||
form.Set("Action", "GetUser")
|
||||
req, _ := http.NewRequest(http.MethodPost, "/", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential="+accessKey+
|
||||
"/20220420/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=fakesig")
|
||||
req = req.WithContext(SetIdentityNameInContext(req.Context(), "TestUser"))
|
||||
|
||||
out := iamGetUserResponse{}
|
||||
rr, err := executeEmbeddedIamRequest(api, req, &out)
|
||||
@@ -1578,29 +1578,15 @@ func TestEmbeddedIamDeleteAccessKey(t *testing.T) {
|
||||
assert.Len(t, api.mockConfig.Identities[0].Credentials, 0)
|
||||
}
|
||||
|
||||
// TestEmbeddedIamHandleImplicitUsername tests implicit username extraction from authorization header
|
||||
// TestEmbeddedIamHandleImplicitUsername checks that the implicit user name is
|
||||
// taken from the authenticated identity in the request context, never from
|
||||
// re-parsing the Authorization header.
|
||||
func TestEmbeddedIamHandleImplicitUsername(t *testing.T) {
|
||||
// Create IAM with test credentials - the handleImplicitUsername function now looks
|
||||
// up the username from the credential store based on AccessKeyId
|
||||
// Note: Using obviously fake access keys to avoid secret scanner false positives
|
||||
iam := &IdentityAccessManagement{}
|
||||
testConfig := &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{
|
||||
Name: "testuser1",
|
||||
Credentials: []*iam_pb.Credential{
|
||||
{AccessKey: UserAccessKeyPrefix + "TESTFAKEKEY000001", SecretKey: "testsecretfake"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
err := iam.LoadS3ApiConfigurationFromBytes(mustMarshalJSON(testConfig))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to load test config: %v", err)
|
||||
}
|
||||
embeddedApi := &EmbeddedIamApi{}
|
||||
|
||||
embeddedApi := &EmbeddedIamApi{
|
||||
iam: iam,
|
||||
withIdentity := func(name string) *http.Request {
|
||||
r := &http.Request{Header: http.Header{}}
|
||||
return r.WithContext(SetIdentityNameInContext(r.Context(), name))
|
||||
}
|
||||
|
||||
var tests = []struct {
|
||||
@@ -1608,14 +1594,14 @@ func TestEmbeddedIamHandleImplicitUsername(t *testing.T) {
|
||||
values url.Values
|
||||
userName string
|
||||
}{
|
||||
// No authorization header - should not set username
|
||||
// No authenticated identity - should not set username
|
||||
{&http.Request{}, url.Values{}, ""},
|
||||
// Valid auth header with known access key - should look up and find "testuser1"
|
||||
{&http.Request{Header: http.Header{"Authorization": []string{"AWS4-HMAC-SHA256 Credential=" + UserAccessKeyPrefix + "TESTFAKEKEY000001/20220420/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=fakesignature0123456789abcdef"}}}, url.Values{}, "testuser1"},
|
||||
// Malformed auth header (no Credential=) - should not set username
|
||||
{&http.Request{Header: http.Header{"Authorization": []string{"AWS4-HMAC-SHA256 =" + UserAccessKeyPrefix + "TESTFAKEKEY000001/20220420/test1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=fakesignature0123456789abcdef"}}}, url.Values{}, ""},
|
||||
// Unknown access key - should not set username
|
||||
{&http.Request{Header: http.Header{"Authorization": []string{"AWS4-HMAC-SHA256 Credential=" + UserAccessKeyPrefix + "TESTUNKNOWN000000/20220420/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=fakesignature0123456789abcdef"}}}, url.Values{}, ""},
|
||||
// Authenticated identity in context - sets its name
|
||||
{withIdentity("testuser1"), url.Values{}, "testuser1"},
|
||||
// A client-controlled Authorization header naming another user is ignored
|
||||
{&http.Request{Header: http.Header{"Authorization": []string{"AWS4-HMAC-SHA256 Credential=" + UserAccessKeyPrefix + "TESTFAKEKEY000001/20220420/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=fakesignature0123456789abcdef"}}}, url.Values{}, ""},
|
||||
// An explicit UserName is left alone
|
||||
{withIdentity("testuser1"), url.Values{"UserName": {"other"}}, "other"},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
|
||||
@@ -181,8 +181,10 @@ func (s3a *S3ApiServer) parseAndValidateRange(w http.ResponseWriter, r *http.Req
|
||||
return 0, totalSize, false, nil
|
||||
}
|
||||
|
||||
// Empty directory: 404. A file promoted to a directory keeps its data and stays retrievable.
|
||||
if entry.IsDirectory && totalSize == 0 {
|
||||
// Empty directory: 404. A file promoted to a directory keeps its data and
|
||||
// stays retrievable, and a stored directory-key marker is an object, not a
|
||||
// missing key — an unsatisfiable range answers 416.
|
||||
if entry.IsDirectory && totalSize == 0 && !entry.IsDirectoryKeyObject() {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
return 0, 0, false, newStreamErrorWithResponse(fmt.Errorf("directory object %s/%s cannot be retrieved", bucket, object))
|
||||
}
|
||||
@@ -533,6 +535,24 @@ func (s3a *S3ApiServer) serveDirectoryContent(w http.ResponseWriter, r *http.Req
|
||||
if r.Method == http.MethodHead && len(entry.Chunks) > 0 {
|
||||
contentLength = int64(entry.Attributes.FileSize)
|
||||
}
|
||||
statusCode := http.StatusOK
|
||||
if r.Header.Get("Range") != "" && requestedPartNumber(r) == 0 {
|
||||
// A ranged request answers like the object path does: 206 with its
|
||||
// Content-Range and the range's length, served on GET, reported on HEAD.
|
||||
totalSize := contentLength
|
||||
offset, size, isRangeRequest, rangeErr := s3a.parseAndValidateRange(w, r, entry, totalSize, bucket, object)
|
||||
if rangeErr != nil {
|
||||
return
|
||||
}
|
||||
if isRangeRequest {
|
||||
contentLength = size
|
||||
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", offset, offset+size-1, totalSize))
|
||||
statusCode = http.StatusPartialContent
|
||||
if r.Method != http.MethodHead {
|
||||
content = content[offset : offset+size]
|
||||
}
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(contentLength, 10))
|
||||
|
||||
// Set last modified
|
||||
@@ -545,12 +565,12 @@ func (s3a *S3ApiServer) serveDirectoryContent(w http.ResponseWriter, r *http.Req
|
||||
|
||||
// For HEAD requests, don't write body
|
||||
if r.Method == http.MethodHead {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.WriteHeader(statusCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Write content
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.WriteHeader(statusCode)
|
||||
if len(content) > 0 {
|
||||
if _, err := w.Write(content); err != nil {
|
||||
glog.Errorf("serveDirectoryContent: failed to write response: %v", err)
|
||||
@@ -2745,6 +2765,17 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", startOffset, endOffset, totalSize))
|
||||
statusCode = http.StatusPartialContent
|
||||
glog.V(3).Infof("HeadObject: part %d is bytes %d-%d/%d", partNumber, startOffset, endOffset, totalSize)
|
||||
} else if r.Header.Get("Range") != "" {
|
||||
// A ranged HEAD reports the range like GET does: 206 with its Content-Range and length
|
||||
offset, size, isRangeRequest, rangeErr := s3a.parseAndValidateRange(w, r, objectEntryForSSE, totalSize, bucket, object)
|
||||
if rangeErr != nil {
|
||||
return
|
||||
}
|
||||
if isRangeRequest {
|
||||
responseSize = size
|
||||
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", offset, offset+size-1, totalSize))
|
||||
statusCode = http.StatusPartialContent
|
||||
}
|
||||
}
|
||||
|
||||
s3a.setResponseHeaders(w, r, objectEntryForSSE, responseSize)
|
||||
|
||||
@@ -2,17 +2,21 @@ package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -1146,7 +1150,9 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
return
|
||||
}
|
||||
|
||||
if uploadEntryHasSSE(uploadEntry) || sourceEntryIsEncrypted(entry) || uploadEntryHasChecksum(uploadEntry) {
|
||||
// Inline-Content sources have no chunks for the raw-byte path to copy;
|
||||
// the plaintext stream serves their range instead.
|
||||
if uploadEntryHasSSE(uploadEntry) || sourceEntryIsEncrypted(entry) || uploadEntryHasChecksum(uploadEntry) || len(entry.Content) > 0 {
|
||||
etag, sseMetadata, errCode := s3a.copyObjectPartViaReencryption(r, entry, startOffset, endOffset, dstBucket, dstObject, uploadID, partID, uploadEntry)
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
@@ -1204,15 +1210,24 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
// For zero-size files or invalid ranges, create an empty part with size 0
|
||||
dstEntry.Attributes.FileSize = 0
|
||||
dstEntry.Chunks = nil
|
||||
dstEntry.Attributes.Md5 = md5.New().Sum(nil)
|
||||
} else {
|
||||
// Copy chunks that overlap with the range
|
||||
dstChunks, err := s3a.copyChunksForRange(entry, startOffset, endOffset, dstAssignPath)
|
||||
dstChunks, partMd5, err := s3a.copyChunksForRange(entry, startOffset, endOffset, dstAssignPath)
|
||||
if err != nil {
|
||||
glog.Errorf("CopyObjectPartHandler copy chunks error: %v", err)
|
||||
s3err.WriteErrorResponse(w, r, s3a.mapCopyErrorToS3Error(err))
|
||||
return
|
||||
}
|
||||
dstEntry.Chunks = dstChunks
|
||||
dstEntry.Attributes.Md5 = partMd5
|
||||
}
|
||||
|
||||
// Mirror putToFiler: the part entry carries the MD5 of its bytes so
|
||||
// CopyPartResult, ListParts and complete's composite ETag all describe
|
||||
// the copied range rather than the source chunks.
|
||||
if len(dstEntry.Attributes.Md5) > 0 {
|
||||
dstEntry.Extended[s3_constants.ExtETagKey] = []byte(fmt.Sprintf("%x", dstEntry.Attributes.Md5))
|
||||
}
|
||||
|
||||
// Save the part entry to the multipart uploads folder
|
||||
@@ -1479,7 +1494,7 @@ func (s3a *S3ApiServer) copySingleChunk(chunk *filer_pb.FileChunk, dstPath strin
|
||||
// the source volume for compressed bytes, so a gzipped chunk is
|
||||
// forwarded to the destination without anyone having to decompress.
|
||||
if canStreamCopyChunk(chunk) {
|
||||
if err := s3a.streamCopyChunkRange(context.Background(), srcUrl, fileId, 0, int64(chunk.Size), true /*isFullChunk*/, assignResult); err != nil {
|
||||
if err := s3a.streamCopyChunkRange(context.Background(), srcUrl, fileId, 0, int64(chunk.Size), true /*isFullChunk*/, assignResult, nil); err != nil {
|
||||
return nil, fmt.Errorf("stream chunk: %w", err)
|
||||
}
|
||||
return dstChunk, nil
|
||||
@@ -1534,9 +1549,22 @@ func (s3a *S3ApiServer) copySingleChunkForRange(originalChunk, rangeChunk *filer
|
||||
// part-size = chunk-size assemble pattern hits this branch.
|
||||
if canStreamCopyChunk(originalChunk) {
|
||||
isFullChunk := offsetInChunk == 0 && rangeChunk.Size == originalChunk.Size
|
||||
if err := s3a.streamCopyChunkRange(context.Background(), srcUrl, fileId, offsetInChunk, int64(rangeChunk.Size), isFullChunk, assignResult); err != nil {
|
||||
// A partial range stores different bytes than the source chunk, so
|
||||
// its ETag has to be recomputed; a whole-chunk copy reuses it.
|
||||
var digest hash.Hash
|
||||
if !isFullChunk {
|
||||
digest = md5.New()
|
||||
}
|
||||
if err := s3a.streamCopyChunkRange(context.Background(), srcUrl, fileId, offsetInChunk, int64(rangeChunk.Size), isFullChunk, assignResult, digest); err != nil {
|
||||
return nil, fmt.Errorf("stream chunk range: %w", err)
|
||||
}
|
||||
if digest != nil {
|
||||
dstChunk.ETag = base64.StdEncoding.EncodeToString(digest.Sum(nil))
|
||||
// The range fetch returns raw bytes and the destination stores
|
||||
// them uncompressed, so the source chunk's gzip flag must not
|
||||
// carry over onto a partial copy.
|
||||
dstChunk.IsCompressed = false
|
||||
}
|
||||
return dstChunk, nil
|
||||
}
|
||||
|
||||
@@ -1609,8 +1637,16 @@ func parseRangeHeader(rangeHeader string, fileSize int64) (startOffset, endOffse
|
||||
return startOffset, endOffset, nil
|
||||
}
|
||||
|
||||
// copyChunksForRange copies chunks that overlap with the specified range
|
||||
func (s3a *S3ApiServer) copyChunksForRange(entry *filer_pb.Entry, startOffset, endOffset int64, dstPath string) ([]*filer_pb.FileChunk, error) {
|
||||
// partMd5Result carries the whole-part MD5 the copiedRangeMd5 goroutine
|
||||
// computes beside the per-chunk copies.
|
||||
type partMd5Result struct {
|
||||
sum []byte
|
||||
err error
|
||||
}
|
||||
|
||||
// copyChunksForRange copies chunks that overlap with the specified range and
|
||||
// returns the MD5 of the copied bytes for the part entry's Attributes.Md5.
|
||||
func (s3a *S3ApiServer) copyChunksForRange(entry *filer_pb.Entry, startOffset, endOffset int64, dstPath string) ([]*filer_pb.FileChunk, []byte, error) {
|
||||
var relevantChunks []*filer_pb.FileChunk
|
||||
var originalChunks []*filer_pb.FileChunk
|
||||
|
||||
@@ -1641,6 +1677,36 @@ func (s3a *S3ApiServer) copyChunksForRange(entry *filer_pb.Entry, startOffset, e
|
||||
}
|
||||
}
|
||||
|
||||
// The part's Attributes.Md5 must cover the copied range in byte order,
|
||||
// and md5 cannot combine per-chunk digests. A single chunk's own digest
|
||||
// is the answer only when it supplies the whole range; anything else —
|
||||
// several chunks, or gaps a sparse source zero-fills — needs an ordered
|
||||
// pass the concurrent copies cannot feed, so a second stream of the
|
||||
// source range hashes beside them.
|
||||
partSize := endOffset - startOffset + 1
|
||||
singleChunkCovers := len(relevantChunks) == 1 &&
|
||||
relevantChunks[0].Offset == 0 && int64(relevantChunks[0].Size) == partSize
|
||||
|
||||
md5Ctx, cancelMd5 := context.WithCancel(context.Background())
|
||||
defer cancelMd5()
|
||||
|
||||
var partMd5 []byte
|
||||
var partMd5Ch chan partMd5Result
|
||||
switch {
|
||||
case singleChunkCovers:
|
||||
// resolved below from the copied chunk's own digest
|
||||
case len(entry.GetChunks()) == 0:
|
||||
// no chunks to read at all: the part is partSize zero bytes (the
|
||||
// stream helper returns empty for a chunkless entry, not zero-fill)
|
||||
partMd5 = md5Zeros(partSize)
|
||||
default:
|
||||
partMd5Ch = make(chan partMd5Result, 1)
|
||||
go func() {
|
||||
sum, err := s3a.copiedRangeMd5(md5Ctx, entry, startOffset, endOffset)
|
||||
partMd5Ch <- partMd5Result{sum, err}
|
||||
}()
|
||||
}
|
||||
|
||||
// Copy the relevant chunks using a specialized method for range copies
|
||||
dstChunks := make([]*filer_pb.FileChunk, len(relevantChunks))
|
||||
const defaultChunkCopyConcurrency = 4
|
||||
@@ -1664,11 +1730,79 @@ func (s3a *S3ApiServer) copyChunksForRange(entry *filer_pb.Entry, startOffset, e
|
||||
// Wait for all operations to complete and check for errors
|
||||
for i := 0; i < len(relevantChunks); i++ {
|
||||
if err := <-errChan; err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return dstChunks, nil
|
||||
// Reads resolve overlapping chunks by ModifiedTsNs, and the concurrent
|
||||
// copies stamped arbitrary finish times: rank the destination chunks by
|
||||
// the source's timestamps so the part resolves overlaps the way the
|
||||
// source did (and the way copiedRangeMd5 hashed it).
|
||||
if len(dstChunks) > 1 {
|
||||
order := make([]int, len(dstChunks))
|
||||
for i := range order {
|
||||
order[i] = i
|
||||
}
|
||||
slices.SortStableFunc(order, func(a, b int) int {
|
||||
return cmp.Compare(originalChunks[a].ModifiedTsNs, originalChunks[b].ModifiedTsNs)
|
||||
})
|
||||
now := time.Now().UnixNano()
|
||||
for rank, i := range order {
|
||||
dstChunks[i].ModifiedTsNs = now + int64(rank)
|
||||
}
|
||||
}
|
||||
|
||||
if partMd5Ch != nil {
|
||||
if res := <-partMd5Ch; res.err != nil {
|
||||
return nil, nil, fmt.Errorf("md5 of copied range: %w", res.err)
|
||||
} else {
|
||||
partMd5 = res.sum
|
||||
}
|
||||
} else if singleChunkCovers {
|
||||
if partMd5 = util.Base64Md5ToBytes(dstChunks[0].ETag); len(partMd5) != md5.Size {
|
||||
// TUS and mount writes leave chunks without an ETag; hash the
|
||||
// copied range when the inherited digest is missing or malformed.
|
||||
sum, err := s3a.copiedRangeMd5(md5Ctx, entry, startOffset, endOffset)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("md5 of copied range: %w", err)
|
||||
}
|
||||
partMd5 = sum
|
||||
}
|
||||
}
|
||||
|
||||
return dstChunks, partMd5, nil
|
||||
}
|
||||
|
||||
// md5Zeros hashes size zero bytes without a volume read — a copied range
|
||||
// that overlaps no source chunk assembles to all zeros.
|
||||
func md5Zeros(size int64) []byte {
|
||||
h := md5.New()
|
||||
var zeros [1 << 16]byte
|
||||
for size > 0 {
|
||||
n := min(size, int64(len(zeros)))
|
||||
h.Write(zeros[:n])
|
||||
size -= n
|
||||
}
|
||||
return h.Sum(nil)
|
||||
}
|
||||
|
||||
// copiedRangeMd5 streams the source range once and hashes its plaintext —
|
||||
// exactly the bytes the non-SSE part copy assembles on the destination.
|
||||
func (s3a *S3ApiServer) copiedRangeMd5(ctx context.Context, entry *filer_pb.Entry, startOffset, endOffset int64) ([]byte, error) {
|
||||
size := endOffset - startOffset + 1
|
||||
// The copy walks the chunks, so the hash must too: on an entry that also
|
||||
// carries inline Content the stream helper would prefer Content instead.
|
||||
chunked := &filer_pb.Entry{Chunks: entry.GetChunks()}
|
||||
reader, err := s3a.getEncryptedStreamFromVolumes(ctx, chunked, startOffset, size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer reader.Close()
|
||||
h := md5.New()
|
||||
if _, err := io.Copy(h, reader); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return h.Sum(nil), nil
|
||||
}
|
||||
|
||||
// Helper methods for copy operations to avoid code duplication
|
||||
|
||||
@@ -160,7 +160,7 @@ func BenchmarkCopyChunk_Streamed(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := s3a.streamCopyChunkRange(context.Background(),
|
||||
env.srcSrv.URL, env.assign.FileId, 0, int64(size),
|
||||
true /*isFullChunk*/, env.assign); err != nil {
|
||||
true /*isFullChunk*/, env.assign, nil); err != nil {
|
||||
b.Fatalf("stream: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -9,6 +14,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
func TestCopyEntryETagPrefersStoredExtendedETag(t *testing.T) {
|
||||
@@ -145,3 +151,292 @@ func TestParseRangeHeaderRejectsUnsatisfiableRange(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A part copied with x-amz-copy-source-range must report the MD5 of the copied
|
||||
// bytes: per destination chunk for a partial-chunk copy, and the whole-part MD5
|
||||
// the part entry's Attributes.Md5 carries for CopyPartResult / ListParts /
|
||||
// complete's composite ETag.
|
||||
func TestCopyChunksForRangeCopiedETags(t *testing.T) {
|
||||
volume := startFakeVolumeServer(t)
|
||||
filerImpl := &ambiguousPutFiler{volume: volume, entries: map[string]*filer_pb.Entry{}}
|
||||
s3a := newPutTestServer(t, startFakeFiler(t, filerImpl))
|
||||
util_http.InitGlobalHttpClient()
|
||||
|
||||
const chunkSize = 4 << 20
|
||||
payload := make([]byte, 2*chunkSize)
|
||||
for i := range payload {
|
||||
payload[i] = byte(i*31 + 7)
|
||||
}
|
||||
b64md5 := func(data []byte) string {
|
||||
sum := md5.Sum(data)
|
||||
return base64.StdEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
fid0 := fmt.Sprintf("3,%016x%08x", 101, 202)
|
||||
fid1 := fmt.Sprintf("3,%016x%08x", 103, 204)
|
||||
volume.stored[fid0] = payload[:chunkSize]
|
||||
volume.stored[fid1] = payload[chunkSize:]
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "src",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileSize: uint64(len(payload)),
|
||||
},
|
||||
Chunks: []*filer_pb.FileChunk{
|
||||
{FileId: fid0, Offset: 0, Size: chunkSize, ETag: b64md5(payload[:chunkSize])},
|
||||
{FileId: fid1, Offset: chunkSize, Size: chunkSize, ETag: b64md5(payload[chunkSize:])},
|
||||
},
|
||||
}
|
||||
|
||||
// A range spanning the first chunk fully plus 1 MiB of the second.
|
||||
multiEnd := int64(chunkSize + 1<<20 - 1)
|
||||
dstChunks, partMd5, err := s3a.copyChunksForRange(entry, 0, multiEnd, "/dst")
|
||||
if err != nil {
|
||||
t.Fatalf("copyChunksForRange: %v", err)
|
||||
}
|
||||
if len(dstChunks) != 2 {
|
||||
t.Fatalf("copyChunksForRange returned %d chunks, want 2", len(dstChunks))
|
||||
}
|
||||
// A whole-chunk copy forwards the stored bytes, so the source ETag stays valid.
|
||||
if got, want := dstChunks[0].ETag, entry.Chunks[0].ETag; got != want {
|
||||
t.Errorf("whole-chunk copy ETag = %q, want source chunk ETag %q", got, want)
|
||||
}
|
||||
// A partial copy stores only the range bytes; its ETag must be their MD5.
|
||||
if got, want := dstChunks[1].ETag, b64md5(payload[chunkSize:multiEnd+1]); got != want {
|
||||
t.Errorf("partial-chunk copy ETag = %q, want copied-bytes MD5 %q", got, want)
|
||||
}
|
||||
// The copied bytes landed on the destination volume (inside the multipart framing).
|
||||
if stored := volume.stored[dstChunks[1].GetFileIdString()]; !bytes.Contains(stored, payload[chunkSize:multiEnd+1]) {
|
||||
t.Error("destination volume does not hold the copied range bytes")
|
||||
}
|
||||
// The whole-part MD5 hashes every copied byte once, in range order.
|
||||
wantPartMd5 := md5.Sum(payload[:multiEnd+1])
|
||||
if !bytes.Equal(partMd5, wantPartMd5[:]) {
|
||||
t.Errorf("part Md5 = %x, want %x", partMd5, wantPartMd5)
|
||||
}
|
||||
partEntry := &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Md5: partMd5},
|
||||
Chunks: dstChunks,
|
||||
}
|
||||
if got, want := copyEntryETag(partEntry), fmt.Sprintf("%x", wantPartMd5); got != want {
|
||||
t.Errorf("copyEntryETag = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
// A range inside one chunk: the part's ETag is the MD5 of those bytes.
|
||||
innerChunks, innerMd5, err := s3a.copyChunksForRange(entry, 100, 199, "/dst")
|
||||
if err != nil {
|
||||
t.Fatalf("copyChunksForRange inner range: %v", err)
|
||||
}
|
||||
if len(innerChunks) != 1 {
|
||||
t.Fatalf("inner range returned %d chunks, want 1", len(innerChunks))
|
||||
}
|
||||
if got, want := innerChunks[0].ETag, b64md5(payload[100:200]); got != want {
|
||||
t.Errorf("inner-range chunk ETag = %q, want copied-bytes MD5 %q", got, want)
|
||||
}
|
||||
wantInnerMd5 := md5.Sum(payload[100:200])
|
||||
if !bytes.Equal(innerMd5, wantInnerMd5[:]) {
|
||||
t.Errorf("inner-range part Md5 = %x, want %x", innerMd5, wantInnerMd5)
|
||||
}
|
||||
}
|
||||
|
||||
// A range over a sparse source zero-fills the gaps, so the part MD5 has to
|
||||
// hash the logical range — not just the one chunk that overlaps it.
|
||||
func TestCopyChunksForRangeSparseETags(t *testing.T) {
|
||||
volume := startFakeVolumeServer(t)
|
||||
filerImpl := &ambiguousPutFiler{volume: volume, entries: map[string]*filer_pb.Entry{}}
|
||||
s3a := newPutTestServer(t, startFakeFiler(t, filerImpl))
|
||||
util_http.InitGlobalHttpClient()
|
||||
|
||||
fid := fmt.Sprintf("3,%016x%08x", 105, 206)
|
||||
volume.stored[fid] = []byte("abc")
|
||||
sum := md5.Sum([]byte("abc"))
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "sparse",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileSize: 6,
|
||||
},
|
||||
Chunks: []*filer_pb.FileChunk{
|
||||
{FileId: fid, Offset: 3, Size: 3, ETag: base64.StdEncoding.EncodeToString(sum[:])},
|
||||
},
|
||||
}
|
||||
|
||||
// bytes 0-5 read as "\x00\x00\x00abc"; the part MD5 must cover the zeros too.
|
||||
dstChunks, partMd5, err := s3a.copyChunksForRange(entry, 0, 5, "/dst")
|
||||
if err != nil {
|
||||
t.Fatalf("copyChunksForRange sparse: %v", err)
|
||||
}
|
||||
if len(dstChunks) != 1 || dstChunks[0].Offset != 3 {
|
||||
t.Fatalf("sparse copy chunks = %+v, want one chunk at offset 3", dstChunks)
|
||||
}
|
||||
wantMd5 := md5.Sum([]byte("\x00\x00\x00abc"))
|
||||
if !bytes.Equal(partMd5, wantMd5[:]) {
|
||||
t.Errorf("sparse part Md5 = %x, want %x (zero-filled range)", partMd5, wantMd5)
|
||||
}
|
||||
|
||||
// A range over a pure hole copies nothing but still reads as zeros.
|
||||
holeChunks, holeMd5, err := s3a.copyChunksForRange(entry, 0, 2, "/dst")
|
||||
if err != nil {
|
||||
t.Fatalf("copyChunksForRange hole: %v", err)
|
||||
}
|
||||
if len(holeChunks) != 0 {
|
||||
t.Fatalf("hole copy returned %d chunks, want 0", len(holeChunks))
|
||||
}
|
||||
wantHoleMd5 := md5.Sum([]byte{0, 0, 0})
|
||||
if !bytes.Equal(holeMd5, wantHoleMd5[:]) {
|
||||
t.Errorf("hole part Md5 = %x, want %x (all zeros)", holeMd5, wantHoleMd5)
|
||||
}
|
||||
}
|
||||
|
||||
// Destination chunks must resolve overlaps the way the source did: reads
|
||||
// pick winners by ModifiedTsNs, so the copied chunks keep the source's
|
||||
// precedence even though they were uploaded concurrently.
|
||||
func TestCopyChunksForRangePreservesSourcePrecedence(t *testing.T) {
|
||||
volume := startFakeVolumeServer(t)
|
||||
filerImpl := &ambiguousPutFiler{volume: volume, entries: map[string]*filer_pb.Entry{}}
|
||||
s3a := newPutTestServer(t, startFakeFiler(t, filerImpl))
|
||||
util_http.InitGlobalHttpClient()
|
||||
|
||||
etagOf := func(b []byte) string {
|
||||
sum := md5.Sum(b)
|
||||
return base64.StdEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
fidA := fmt.Sprintf("3,%016x%08x", 107, 208)
|
||||
fidB := fmt.Sprintf("3,%016x%08x", 109, 210)
|
||||
volume.stored[fidA] = []byte("aaaa")
|
||||
volume.stored[fidB] = []byte("bbbb")
|
||||
|
||||
// A covers [0,4), B covers [2,6); B's range is copied into a chunk that
|
||||
// overlaps A's copy on [2,4), and the source says A wins there.
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "overlap",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 6},
|
||||
Chunks: []*filer_pb.FileChunk{
|
||||
{FileId: fidA, Offset: 0, Size: 4, ModifiedTsNs: 20, ETag: etagOf([]byte("aaaa"))},
|
||||
{FileId: fidB, Offset: 2, Size: 4, ModifiedTsNs: 10, ETag: etagOf([]byte("bbbb"))},
|
||||
},
|
||||
}
|
||||
dstChunks, partMd5, err := s3a.copyChunksForRange(entry, 0, 5, "/dst")
|
||||
if err != nil {
|
||||
t.Fatalf("copyChunksForRange overlap: %v", err)
|
||||
}
|
||||
if len(dstChunks) != 2 {
|
||||
t.Fatalf("overlap copy returned %d chunks, want 2", len(dstChunks))
|
||||
}
|
||||
if dstChunks[0].ModifiedTsNs <= dstChunks[1].ModifiedTsNs {
|
||||
t.Errorf("destination precedence inverted: chunk from ts=20 got %d, chunk from ts=10 got %d",
|
||||
dstChunks[0].ModifiedTsNs, dstChunks[1].ModifiedTsNs)
|
||||
}
|
||||
// The source resolves to "aaaa"+"bb"; the part MD5 must match that view.
|
||||
wantMd5 := md5.Sum([]byte("aaaabb"))
|
||||
if !bytes.Equal(partMd5, wantMd5[:]) {
|
||||
t.Errorf("overlap part Md5 = %x, want %x", partMd5, wantMd5)
|
||||
}
|
||||
}
|
||||
|
||||
// An inline-Content source has no chunks for the raw-byte copy; the plaintext
|
||||
// stream path must write the range's real bytes and tag the part with their
|
||||
// MD5, not a zero-fill digest.
|
||||
func TestCopyObjectPartInlineContent(t *testing.T) {
|
||||
volume := startFakeVolumeServer(t)
|
||||
filerImpl := &ambiguousPutFiler{volume: volume, apply: true, entries: map[string]*filer_pb.Entry{}}
|
||||
s3a := newPutTestServer(t, startFakeFiler(t, filerImpl))
|
||||
util_http.InitGlobalHttpClient()
|
||||
|
||||
content := []byte("inline-content")
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "src",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(content))},
|
||||
Content: content,
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodPut, "/b/dst?partNumber=1&uploadId=u1", nil)
|
||||
etag, _, code := s3a.copyObjectPartViaReencryption(r, entry, 2, 5, "b", "dst", "u1", 1, &filer_pb.Entry{})
|
||||
if code != s3err.ErrNone {
|
||||
t.Fatalf("copyObjectPartViaReencryption: %v", code)
|
||||
}
|
||||
wantMd5 := md5.Sum(content[2:6])
|
||||
if got := strings.Trim(etag, `"`); got != fmt.Sprintf("%x", wantMd5) {
|
||||
t.Errorf("etag = %q, want %x", got, wantMd5)
|
||||
}
|
||||
var partEntry *filer_pb.Entry
|
||||
for key, e := range filerImpl.entries {
|
||||
if strings.Contains(key, "u1") {
|
||||
partEntry = e
|
||||
}
|
||||
}
|
||||
if partEntry == nil || len(partEntry.Chunks) == 0 {
|
||||
t.Fatalf("no part entry with chunks stored: %+v", filerImpl.entries)
|
||||
}
|
||||
found := false
|
||||
for _, stored := range volume.stored {
|
||||
if bytes.Contains(stored, content[2:6]) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("destination volume does not hold the copied content bytes")
|
||||
}
|
||||
}
|
||||
|
||||
// An empty part must carry the empty-body MD5 on the stored entry too, so
|
||||
// ListParts and complete's composite ETag see the same digest CopyPartResult
|
||||
// reported.
|
||||
func TestWriteEmptyCopyPartStoresMd5(t *testing.T) {
|
||||
volume := startFakeVolumeServer(t)
|
||||
filerImpl := &ambiguousPutFiler{volume: volume, apply: true, entries: map[string]*filer_pb.Entry{}}
|
||||
s3a := newPutTestServer(t, startFakeFiler(t, filerImpl))
|
||||
util_http.InitGlobalHttpClient()
|
||||
|
||||
etag, code := s3a.writeEmptyCopyPart("b", "u1", 3)
|
||||
if code != s3err.ErrNone {
|
||||
t.Fatalf("writeEmptyCopyPart: %v", code)
|
||||
}
|
||||
const emptyMD5Hex = "d41d8cd98f00b204e9800998ecf8427e"
|
||||
if etag != emptyMD5Hex {
|
||||
t.Fatalf("writeEmptyCopyPart etag = %q, want %q", etag, emptyMD5Hex)
|
||||
}
|
||||
var partEntry *filer_pb.Entry
|
||||
for key, e := range filerImpl.entries {
|
||||
if strings.Contains(key, "u1") {
|
||||
partEntry = e
|
||||
}
|
||||
}
|
||||
if partEntry == nil {
|
||||
t.Fatalf("no part entry stored: %+v", filerImpl.entries)
|
||||
}
|
||||
if got := string(partEntry.Extended[s3_constants.ExtETagKey]); got != emptyMD5Hex {
|
||||
t.Errorf("stored ExtETagKey = %q, want %q", got, emptyMD5Hex)
|
||||
}
|
||||
if got := fmt.Sprintf("%x", partEntry.Attributes.Md5); got != emptyMD5Hex {
|
||||
t.Errorf("stored Attributes.Md5 = %q, want %q", got, emptyMD5Hex)
|
||||
}
|
||||
}
|
||||
|
||||
// A whole-range chunk copy normally reuses the source chunk's ETag as the
|
||||
// part MD5; TUS and mount writes leave chunks without one, so the part has
|
||||
// to hash the copied bytes instead of saving an empty digest.
|
||||
func TestCopyChunksForRangeMissingChunkETag(t *testing.T) {
|
||||
volume := startFakeVolumeServer(t)
|
||||
filerImpl := &ambiguousPutFiler{volume: volume, entries: map[string]*filer_pb.Entry{}}
|
||||
s3a := newPutTestServer(t, startFakeFiler(t, filerImpl))
|
||||
util_http.InitGlobalHttpClient()
|
||||
|
||||
fid := fmt.Sprintf("3,%016x%08x", 111, 212)
|
||||
volume.stored[fid] = []byte("etagless")
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "src",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 8},
|
||||
Chunks: []*filer_pb.FileChunk{
|
||||
{FileId: fid, Offset: 0, Size: 8},
|
||||
},
|
||||
}
|
||||
|
||||
dstChunks, partMd5, err := s3a.copyChunksForRange(entry, 0, 7, "/dst")
|
||||
if err != nil {
|
||||
t.Fatalf("copyChunksForRange: %v", err)
|
||||
}
|
||||
if len(dstChunks) != 1 {
|
||||
t.Fatalf("copyChunksForRange returned %d chunks, want 1", len(dstChunks))
|
||||
}
|
||||
wantMd5 := md5.Sum([]byte("etagless"))
|
||||
if !bytes.Equal(partMd5, wantMd5[:]) {
|
||||
t.Errorf("part Md5 = %x, want %x (hashed copied range)", partMd5, wantMd5)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -419,14 +420,19 @@ func (s3a *S3ApiServer) writeEmptyCopyPart(dstBucket, uploadID string, partID in
|
||||
return "", s3err.ErrInternalError
|
||||
}
|
||||
}
|
||||
const emptyMD5Hex = "d41d8cd98f00b204e9800998ecf8427e"
|
||||
if err := s3a.mkFile(uploadDir, partName, nil, func(e *filer_pb.Entry) {
|
||||
if e.Attributes == nil {
|
||||
e.Attributes = &filer_pb.FuseAttributes{}
|
||||
}
|
||||
e.Attributes.FileSize = 0
|
||||
e.Attributes.Md5 = md5.New().Sum(nil)
|
||||
if e.Extended == nil {
|
||||
e.Extended = map[string][]byte{}
|
||||
}
|
||||
e.Extended[s3_constants.ExtETagKey] = []byte(emptyMD5Hex)
|
||||
}); err != nil {
|
||||
return "", s3err.ErrInternalError
|
||||
}
|
||||
const emptyMD5Hex = "d41d8cd98f00b204e9800998ecf8427e"
|
||||
return emptyMD5Hex, s3err.ErrNone
|
||||
}
|
||||
@@ -73,12 +73,19 @@ func canStreamCopyChunk(chunk *filer_pb.FileChunk) bool {
|
||||
// Trusting a hint that disagrees with the wire bytes (e.g. caller says
|
||||
// "compressed" but the volume returned raw bytes for a partial range)
|
||||
// would label raw bytes as gzip and corrupt reads on the destination.
|
||||
//
|
||||
// digestWriter, when non-nil, receives the plaintext bytes as they are
|
||||
// forwarded so the caller can derive the destination chunk's ETag. It is
|
||||
// not fed when the wire bytes are gzip — only possible on the full-chunk
|
||||
// pass-through, whose logical content still matches the source chunk's
|
||||
// own ETag and needs no recomputation.
|
||||
func (s3a *S3ApiServer) streamCopyChunkRange(
|
||||
ctx context.Context,
|
||||
srcUrl, srcFileId string,
|
||||
offset, size int64,
|
||||
isFullChunk bool,
|
||||
assignResult *filer_pb.AssignVolumeResponse,
|
||||
digestWriter io.Writer,
|
||||
) error {
|
||||
// Range header takes int64, but mirror the int32 bound from
|
||||
// downloadChunkData so the two paths reject the same inputs.
|
||||
@@ -166,7 +173,11 @@ func (s3a *S3ApiServer) streamCopyChunkRange(
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := io.Copy(fw, srcResp.Body); err != nil {
|
||||
src := io.Reader(srcResp.Body)
|
||||
if digestWriter != nil && !bodyIsGzipped {
|
||||
src = io.TeeReader(srcResp.Body, digestWriter)
|
||||
}
|
||||
if _, err := io.Copy(fw, src); err != nil {
|
||||
if shouldLogStreamError(err) {
|
||||
glog.V(2).Infof("stream copy %s offset=%d size=%d: %v",
|
||||
srcUrl, offset, size, err)
|
||||
|
||||
@@ -87,7 +87,7 @@ func TestCopyChunksReadOnlyIsAccessDenied(t *testing.T) {
|
||||
t.Fatalf("copyChunks err %v maps to %v, want %v", err, code, s3err.ErrAccessDenied)
|
||||
}
|
||||
|
||||
_, err = s3a.copyChunksForRange(entry, 0, 7, "/buckets/b/dst")
|
||||
_, _, err = s3a.copyChunksForRange(entry, 0, 7, "/buckets/b/dst")
|
||||
if code := s3a.mapCopyErrorToS3Error(err); code != s3err.ErrAccessDenied {
|
||||
t.Fatalf("copyChunksForRange err %v maps to %v, want %v", err, code, s3err.ErrAccessDenied)
|
||||
}
|
||||
|
||||
@@ -40,3 +40,33 @@ func TestParseAndValidateRangeRejectsMalformedNumericOffsets(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeadObjectRange(t *testing.T) {
|
||||
s3a, f := newAnonymousReadTestServer(t)
|
||||
f.entries["/buckets/b/o"] = anonymousReadEntry(anonymousReadGrant("READ"))
|
||||
for _, tc := range []struct {
|
||||
rangeHeader, contentRange, contentLength string
|
||||
code int
|
||||
}{
|
||||
{"", "", "11", http.StatusOK},
|
||||
{"bytes=1-4", "bytes 1-4/11", "4", http.StatusPartialContent},
|
||||
{"bytes=-3", "bytes 8-10/11", "3", http.StatusPartialContent},
|
||||
{"bytes=5-", "bytes 5-10/11", "6", http.StatusPartialContent},
|
||||
{"bytes=20-", "bytes */11", "", http.StatusRequestedRangeNotSatisfiable},
|
||||
} {
|
||||
headers := map[string]string{}
|
||||
if tc.rangeHeader != "" {
|
||||
headers["Range"] = tc.rangeHeader
|
||||
}
|
||||
rr := serveAnonymousRead(s3a, http.MethodHead, "o", "", headers)
|
||||
if rr.Code != tc.code {
|
||||
t.Errorf("Range %q: status %d, want %d", tc.rangeHeader, rr.Code, tc.code)
|
||||
}
|
||||
if got := rr.Header().Get("Content-Range"); got != tc.contentRange {
|
||||
t.Errorf("Range %q: Content-Range %q, want %q", tc.rangeHeader, got, tc.contentRange)
|
||||
}
|
||||
if got := rr.Header().Get("Content-Length"); tc.contentLength != "" && got != tc.contentLength {
|
||||
t.Errorf("Range %q: Content-Length %q, want %q", tc.rangeHeader, got, tc.contentLength)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -459,6 +459,70 @@ func isAuthError(err error) bool {
|
||||
return errors.As(err, &authErr) || errors.Is(err, ErrAccessDenied)
|
||||
}
|
||||
|
||||
// authorizeAbsentTarget reports whether the caller may learn the target
|
||||
// resolved to nothing, so a caller without a grant gets the same response a
|
||||
// denied existing target would give. The bucket named by the target still
|
||||
// applies whatever metadata and policy load; with nothing readable to
|
||||
// evaluate, only an identity-level grant on the operation, the admin, or a
|
||||
// default-allow deployment passes.
|
||||
func (h *S3TablesHandler) authorizeAbsentTarget(r *http.Request, filerClient FilerClient, operation, bucketName, namespace, name, resourceARN string) bool {
|
||||
principal := h.getAccountID(r)
|
||||
if principal == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
var bucketOwner, bucketPolicy string
|
||||
var bucketTags map[string]string
|
||||
if bucketName != "" {
|
||||
bucketPath := GetTableBucketPath(bucketName)
|
||||
_ = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
if data, err := h.getExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyMetadata); err == nil {
|
||||
var meta tableBucketMetadata
|
||||
if json.Unmarshal(data, &meta) == nil {
|
||||
bucketOwner = meta.OwnerAccountID
|
||||
}
|
||||
}
|
||||
if policy, err := h.readPolicy(r, client, bucketPath); err == nil {
|
||||
bucketPolicy = policy
|
||||
}
|
||||
bucketTags, _ = h.readTags(r.Context(), client, bucketPath)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
bucketARN := h.generateTableBucketARN(bucketOwner, bucketName)
|
||||
// Judge the target by the canonical ARN the surviving bucket resolves to:
|
||||
// the request ARN's account and region are the caller's to choose and must
|
||||
// not decide whether a policy Deny applies.
|
||||
canonicalARN := resourceARN
|
||||
if bucketOwner != "" {
|
||||
if name != "" {
|
||||
canonicalARN = h.generateTableARN(bucketOwner, bucketName, namespace+"/"+name)
|
||||
} else {
|
||||
canonicalARN = bucketARN
|
||||
}
|
||||
}
|
||||
ctx := &PolicyContext{
|
||||
TrustedIssuers: h.trustedIssuers(r),
|
||||
IsLocalAccountID: h.localAccountIDs,
|
||||
TableBucketName: bucketName,
|
||||
Namespace: namespace,
|
||||
TableName: name,
|
||||
TableBucketTags: bucketTags,
|
||||
IdentityActions: getIdentityActions(r),
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}
|
||||
if resourceARN != "" &&
|
||||
matchesDenyStatement(operation, principal, bucketPolicy, canonicalARN, ctx) {
|
||||
return false
|
||||
}
|
||||
if CheckTableOrBucketPermission(operation, principal, "", "", canonicalARN,
|
||||
bucketOwner, bucketPolicy, bucketARN, ctx) {
|
||||
return true
|
||||
}
|
||||
return bucketOwner == "" && checkPermission(operation, principal, "", "", resourceARN, ctx)
|
||||
}
|
||||
|
||||
func (h *S3TablesHandler) readTags(ctx context.Context, client filer_pb.SeaweedFilerClient, path string) (map[string]string, error) {
|
||||
data, err := h.getExtendedAttribute(ctx, client, path, ExtendedKeyTags)
|
||||
if err != nil {
|
||||
|
||||
@@ -58,7 +58,7 @@ func (h *S3TablesHandler) handleGetTableBucket(w http.ResponseWriter, r *http.Re
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrAttributeNotFound) {
|
||||
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName))
|
||||
} else {
|
||||
h.writeError(w, http.StatusInternalServerError, ErrCodeInternalError, fmt.Sprintf("failed to get table bucket: %v", err))
|
||||
|
||||
@@ -3,6 +3,7 @@ package s3tables
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
@@ -211,3 +212,165 @@ func TestDeniedTableWritesDoNotRevealViews(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A caller without a grant must get the same answer whether a list target
|
||||
// exists or not, and whether the bucket behind it exists at all.
|
||||
func TestAbsentListTargetsMatchDeniedAnswers(t *testing.T) {
|
||||
existing, manager := startRenameManager(t)
|
||||
missing := s3tablestest.Start(t)
|
||||
manager.SetTrusted(false)
|
||||
manager.SetDefaultAllow(false)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
fs *s3tablestest.MemFiler
|
||||
operation string
|
||||
denied interface{}
|
||||
request interface{}
|
||||
}{
|
||||
{"ListTables missing namespace", existing, "ListTables",
|
||||
&ListTablesRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}},
|
||||
&ListTablesRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ghost"}}},
|
||||
{"ListTables missing bucket", missing, "ListTables",
|
||||
&ListTablesRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}},
|
||||
&ListTablesRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}}},
|
||||
{"ListTables missing bucket, all namespaces", missing, "ListTables",
|
||||
&ListTablesRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}},
|
||||
&ListTablesRequest{TableBucketARN: mustBucketARN(t)}},
|
||||
{"ListViews missing namespace", existing, "ListViews",
|
||||
&ListViewsRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}},
|
||||
&ListViewsRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ghost"}}},
|
||||
{"CreateNamespace missing bucket", missing, "CreateNamespace",
|
||||
&CreateNamespaceRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"newns"}},
|
||||
&CreateNamespaceRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"newns"}}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
denied := runUnauthorizedRequest(t, manager, existing, tc.operation, tc.denied)
|
||||
assert.Equal(t, 403, denied.status)
|
||||
got := runUnauthorizedRequest(t, manager, tc.fs, tc.operation, tc.request)
|
||||
assert.Equal(t, denied, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A denied tag operation and the same operation on a missing table must answer
|
||||
// alike; a granted caller still gets the truthful not-found.
|
||||
func TestAbsentTagTargetsMatchDeniedAnswers(t *testing.T) {
|
||||
existing, manager := startRenameManager(t)
|
||||
manager.SetTrusted(false)
|
||||
manager.SetDefaultAllow(false)
|
||||
|
||||
existingARN, err := BuildTableARN(DefaultRegion, DefaultAccountID, renameTestBucket, "ns", "t")
|
||||
require.NoError(t, err)
|
||||
missingARN, err := BuildTableARN(DefaultRegion, DefaultAccountID, renameTestBucket, "ns", "ghost")
|
||||
require.NoError(t, err)
|
||||
|
||||
requestFor := func(operation, arn string) interface{} {
|
||||
switch operation {
|
||||
case "TagResource":
|
||||
return &TagResourceRequest{ResourceARN: arn, Tags: map[string]string{"k": "v"}}
|
||||
case "UntagResource":
|
||||
return &UntagResourceRequest{ResourceARN: arn, TagKeys: []string{"k"}}
|
||||
}
|
||||
return &ListTagsForResourceRequest{ResourceARN: arn}
|
||||
}
|
||||
|
||||
for _, operation := range []string{"TagResource", "ListTagsForResource", "UntagResource"} {
|
||||
t.Run(operation, func(t *testing.T) {
|
||||
denied := runUnauthorizedRequest(t, manager, existing, operation, requestFor(operation, existingARN))
|
||||
assert.Equal(t, 403, denied.status)
|
||||
got := runUnauthorizedRequest(t, manager, existing, operation, requestFor(operation, missingARN))
|
||||
assert.Equal(t, denied, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A directory that holds a plain S3 bucket name is not a table bucket: every
|
||||
// caller gets the same 404 an absent name gets, not a 500 that reveals the
|
||||
// name resolves in the filer.
|
||||
func TestPlainBucketReadsAsAbsent(t *testing.T) {
|
||||
existing, manager := startRenameManager(t)
|
||||
manager.SetTrusted(false)
|
||||
manager.SetDefaultAllow(false)
|
||||
existing.Put(TablesPath, "plainbkt", nil)
|
||||
|
||||
plainARN, err := BuildBucketARN(DefaultRegion, DefaultAccountID, "plainbkt")
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, tc := range []struct {
|
||||
operation string
|
||||
request interface{}
|
||||
}{
|
||||
{"GetTableBucket", &GetTableBucketRequest{TableBucketARN: plainARN}},
|
||||
{"ListNamespaces", &ListNamespacesRequest{TableBucketARN: plainARN}},
|
||||
} {
|
||||
t.Run(tc.operation, func(t *testing.T) {
|
||||
got := runUnauthorizedRequest(t, manager, existing, tc.operation, tc.request)
|
||||
assert.Equal(t, 404, got.status)
|
||||
assert.Equal(t, ErrCodeNoSuchBucket, got.body.Type)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A caller with an identity-level grant still learns that a name is absent.
|
||||
func TestGrantedCallerLearnsAbsence(t *testing.T) {
|
||||
missing := s3tablestest.Start(t)
|
||||
manager := NewManager()
|
||||
manager.SetTrusted(false)
|
||||
manager.SetDefaultAllow(false)
|
||||
|
||||
got := runRequestAs(t, manager, missing, "ListTables", &ListTablesRequest{
|
||||
TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}},
|
||||
[]string{"s3tables:ListTables"})
|
||||
assert.Equal(t, 200, got.status)
|
||||
|
||||
missingTableARN, err := BuildTableARN(DefaultRegion, DefaultAccountID, renameTestBucket, "ns", "ghost")
|
||||
require.NoError(t, err)
|
||||
got = runRequestAs(t, manager, missing, "ListTagsForResource",
|
||||
&ListTagsForResourceRequest{ResourceARN: missingTableARN},
|
||||
[]string{"s3tables:ListTagsForResource"})
|
||||
assert.Equal(t, 404, got.status)
|
||||
assert.Equal(t, ErrCodeNoSuchTable, got.body.Type)
|
||||
}
|
||||
|
||||
// A request ARN that names a foreign account still resolves to the local
|
||||
// names, so the absent-target answer must match the denial the canonical ARN
|
||||
// gets; otherwise a reformatted ARN restores the existence oracle.
|
||||
func TestAbsentTagTargetDenySurvivesForeignAccountARN(t *testing.T) {
|
||||
fs, manager := startRenameManager(t)
|
||||
manager.SetTrusted(false)
|
||||
manager.SetDefaultAllow(false)
|
||||
|
||||
bucketMeta, _ := json.Marshal(tableBucketMetadata{Name: renameTestBucket, OwnerAccountID: DefaultAccountID})
|
||||
fs.Put(TablesPath, renameTestBucket, map[string][]byte{
|
||||
ExtendedKeyTableBucket: []byte("{}"),
|
||||
ExtendedKeyMetadata: bucketMeta,
|
||||
ExtendedKeyPolicy: []byte(fmt.Sprintf(
|
||||
`{"Statement":[{"Effect":"Deny","Principal":"*","Action":"s3tables:*","Resource":%q}]}`,
|
||||
mustBucketARN(t)+"/table/*")),
|
||||
})
|
||||
|
||||
foreignARN := func(table string) string {
|
||||
return fmt.Sprintf("arn:aws:s3tables:%s:999999999999:bucket/%s/table/ns/%s",
|
||||
DefaultRegion, renameTestBucket, table)
|
||||
}
|
||||
requestFor := func(operation, arn string) interface{} {
|
||||
switch operation {
|
||||
case "TagResource":
|
||||
return &TagResourceRequest{ResourceARN: arn, Tags: map[string]string{"k": "v"}}
|
||||
case "UntagResource":
|
||||
return &UntagResourceRequest{ResourceARN: arn, TagKeys: []string{"k"}}
|
||||
}
|
||||
return &ListTagsForResourceRequest{ResourceARN: arn}
|
||||
}
|
||||
|
||||
for _, operation := range []string{"TagResource", "ListTagsForResource", "UntagResource"} {
|
||||
t.Run(operation, func(t *testing.T) {
|
||||
actions := []string{"s3tables:" + operation}
|
||||
denied := runRequestAs(t, manager, fs, operation, requestFor(operation, foreignARN("t")), actions)
|
||||
assert.Equal(t, 403, denied.status)
|
||||
got := runRequestAs(t, manager, fs, operation, requestFor(operation, foreignARN("ghost")), actions)
|
||||
assert.Equal(t, denied, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -140,6 +140,10 @@ func (h *S3TablesHandler) handleCreateNamespace(w http.ResponseWriter, r *http.R
|
||||
return ErrAccessDenied
|
||||
}
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
if !h.authorizeAbsentTarget(r, filerClient, "CreateNamespace", bucketName, namespaceName, "", "") {
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to create namespace in this bucket")
|
||||
return ErrAccessDenied
|
||||
}
|
||||
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName))
|
||||
} else {
|
||||
h.writeError(w, http.StatusInternalServerError, ErrCodeInternalError, fmt.Sprintf("failed to check table bucket: %v", err))
|
||||
@@ -481,7 +485,7 @@ func (h *S3TablesHandler) handleListNamespaces(w http.ResponseWriter, r *http.Re
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrAttributeNotFound) {
|
||||
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName))
|
||||
} else {
|
||||
h.writeError(w, http.StatusInternalServerError, ErrCodeInternalError, fmt.Sprintf("failed to list namespaces: %v", err))
|
||||
|
||||
@@ -659,6 +659,9 @@ func (h *S3TablesHandler) handleTagResource(w http.ResponseWriter, r *http.Reque
|
||||
// Read metadata for ownership check
|
||||
data, err := h.getExtendedAttribute(r.Context(), client, resourcePath, ExtendedKeyMetadata)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrAttributeNotFound) {
|
||||
return h.absentTagTargetError(r, client, "TagResource", "not authorized to tag resource", req.ResourceARN, rType)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -793,6 +796,9 @@ func (h *S3TablesHandler) handleListTagsForResource(w http.ResponseWriter, r *ht
|
||||
// Read metadata for ownership check
|
||||
data, err := h.getExtendedAttribute(r.Context(), client, resourcePath, ExtendedKeyMetadata)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrAttributeNotFound) {
|
||||
return h.absentTagTargetError(r, client, "ListTagsForResource", "not authorized to list tags for resource", req.ResourceARN, rType)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -913,6 +919,9 @@ func (h *S3TablesHandler) handleUntagResource(w http.ResponseWriter, r *http.Req
|
||||
// Read metadata for ownership check
|
||||
data, err := h.getExtendedAttribute(r.Context(), client, resourcePath, ExtendedKeyMetadata)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrAttributeNotFound) {
|
||||
return h.absentTagTargetError(r, client, "UntagResource", "not authorized to untag resource", req.ResourceARN, rType)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1017,6 +1026,22 @@ func (h *S3TablesHandler) handleUntagResource(w http.ResponseWriter, r *http.Req
|
||||
return nil
|
||||
}
|
||||
|
||||
// absentTagTargetError resolves a tag operation when the resource's catalog
|
||||
// metadata did not load: a caller the operation would refuse gets its denial,
|
||||
// everyone else the same not-found an absent name gets.
|
||||
func (h *S3TablesHandler) absentTagTargetError(r *http.Request, client filer_pb.SeaweedFilerClient, operation, deniedMessage, resourceARN string, rType ResourceType) error {
|
||||
var bucketName, namespace, name string
|
||||
if rType == ResourceTypeTable {
|
||||
bucketName, namespace, name, _ = parseTableFromARN(resourceARN)
|
||||
} else {
|
||||
bucketName, _ = parseBucketNameFromARN(resourceARN)
|
||||
}
|
||||
if !h.authorizeAbsentTarget(r, &singleClient{client}, operation, bucketName, namespace, name, resourceARN) {
|
||||
return NewAuthError(operation, h.getAccountID(r), deniedMessage)
|
||||
}
|
||||
return filer_pb.ErrNotFound
|
||||
}
|
||||
|
||||
// resolveResourcePath determines the resource path and extended attribute key from a resource ARN
|
||||
func (h *S3TablesHandler) resolveResourcePath(resourceARN string) (path string, key string, rType ResourceType, err error) {
|
||||
// Try parsing as table ARN first
|
||||
|
||||
@@ -515,11 +515,14 @@ func (h *S3TablesHandler) handleListTables(w http.ResponseWriter, r *http.Reques
|
||||
bucketTags := map[string]string{}
|
||||
|
||||
// Fetch namespace metadata and policy
|
||||
targetAbsent := false
|
||||
data, err := h.getExtendedAttribute(r.Context(), client, namespacePath, ExtendedKeyMetadata)
|
||||
if err != nil {
|
||||
return err // Not Found handled by caller
|
||||
}
|
||||
if err := json.Unmarshal(data, &nsMeta); err != nil {
|
||||
if !errors.Is(err, filer_pb.ErrNotFound) && !errors.Is(err, ErrAttributeNotFound) {
|
||||
return err
|
||||
}
|
||||
targetAbsent = true
|
||||
} else if err := json.Unmarshal(data, &nsMeta); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -527,7 +530,7 @@ func (h *S3TablesHandler) handleListTables(w http.ResponseWriter, r *http.Reques
|
||||
policyData, err := h.getExtendedAttribute(r.Context(), client, namespacePath, ExtendedKeyPolicy)
|
||||
if err == nil {
|
||||
namespacePolicy = string(policyData)
|
||||
} else if !errors.Is(err, ErrAttributeNotFound) {
|
||||
} else if !errors.Is(err, ErrAttributeNotFound) && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return fmt.Errorf("failed to fetch namespace policy: %w", err)
|
||||
}
|
||||
|
||||
@@ -537,6 +540,8 @@ func (h *S3TablesHandler) handleListTables(w http.ResponseWriter, r *http.Reques
|
||||
if err := json.Unmarshal(data, &bucketMeta); err != nil {
|
||||
return fmt.Errorf("failed to unmarshal bucket metadata: %w", err)
|
||||
}
|
||||
} else if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
targetAbsent = true
|
||||
} else if !errors.Is(err, ErrAttributeNotFound) {
|
||||
return fmt.Errorf("failed to fetch bucket metadata: %w", err)
|
||||
}
|
||||
@@ -544,15 +549,24 @@ func (h *S3TablesHandler) handleListTables(w http.ResponseWriter, r *http.Reques
|
||||
policyData, err = h.getExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyPolicy)
|
||||
if err == nil {
|
||||
bucketPolicy = string(policyData)
|
||||
} else if !errors.Is(err, ErrAttributeNotFound) {
|
||||
} else if !errors.Is(err, ErrAttributeNotFound) && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return fmt.Errorf("failed to fetch bucket policy: %w", err)
|
||||
}
|
||||
if tags, err := h.readTags(r.Context(), client, bucketPath); err != nil {
|
||||
return fmt.Errorf("failed to read bucket tags: %w", err)
|
||||
if !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return fmt.Errorf("failed to read bucket tags: %w", err)
|
||||
}
|
||||
} else if tags != nil {
|
||||
bucketTags = tags
|
||||
}
|
||||
|
||||
if targetAbsent {
|
||||
if !h.authorizeAbsentTarget(r, &singleClient{client}, "ListTables", bucketName, namespaceName, "", "") {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
return filer_pb.ErrNotFound
|
||||
}
|
||||
|
||||
bucketARN := h.generateTableBucketARN(bucketMeta.OwnerAccountID, bucketName)
|
||||
identityActions := getIdentityActions(r)
|
||||
if !CheckTableOrBucketPermission("ListTables", accountID,
|
||||
@@ -583,7 +597,13 @@ func (h *S3TablesHandler) handleListTables(w http.ResponseWriter, r *http.Reques
|
||||
// Fetch bucket metadata and policy
|
||||
data, err := h.getExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyMetadata)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch bucket metadata: %w", err)
|
||||
if !errors.Is(err, filer_pb.ErrNotFound) && !errors.Is(err, ErrAttributeNotFound) {
|
||||
return fmt.Errorf("failed to fetch bucket metadata: %w", err)
|
||||
}
|
||||
if !h.authorizeAbsentTarget(r, &singleClient{client}, "ListTables", bucketName, "", "", "") {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
return filer_pb.ErrNotFound
|
||||
}
|
||||
if err := json.Unmarshal(data, &bucketMeta); err != nil {
|
||||
return fmt.Errorf("failed to unmarshal bucket metadata: %w", err)
|
||||
|
||||
@@ -279,7 +279,13 @@ func (h *S3TablesHandler) handleListViews(w http.ResponseWriter, r *http.Request
|
||||
var nsMeta namespaceMetadata
|
||||
data, err := h.getExtendedAttribute(r.Context(), client, namespacePath, ExtendedKeyMetadata)
|
||||
if err != nil {
|
||||
return err
|
||||
if !errors.Is(err, filer_pb.ErrNotFound) && !errors.Is(err, ErrAttributeNotFound) {
|
||||
return err
|
||||
}
|
||||
if !h.authorizeAbsentTarget(r, &singleClient{client}, "ListViews", bucketName, namespaceName, "", "") {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
return filer_pb.ErrNotFound
|
||||
}
|
||||
if err := json.Unmarshal(data, &nsMeta); err != nil {
|
||||
return err
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
// - metadata/v*.metadata.json (table metadata)
|
||||
// - metadata/snap-*.avro (snapshot manifest lists)
|
||||
// - metadata/*.avro (manifest files)
|
||||
// - metadata/*.stats, metadata/*.puffin (statistics files)
|
||||
// - data/*.parquet, *.orc, *.avro, *.puffin (data files)
|
||||
|
||||
const uuidPattern = `[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}`
|
||||
@@ -68,6 +69,9 @@ var (
|
||||
// whose naming we can't anticipate across engines and versions.
|
||||
regexp.MustCompile(`^[A-Za-z0-9._-]+\.avro$`),
|
||||
regexp.MustCompile(`^[A-Za-z0-9._-]+\.metadata\.json$`),
|
||||
// Table and partition statistics files listed in the table metadata
|
||||
// are Puffin files; engines name them *.stats or *.puffin.
|
||||
regexp.MustCompile(`^[A-Za-z0-9._-]+\.puffin$`),
|
||||
}
|
||||
|
||||
// Patterns for valid data files
|
||||
|
||||
@@ -45,6 +45,10 @@ func TestIcebergLayoutValidator_AcceptsRealWorldManifestNames(t *testing.T) {
|
||||
"trino/iceberg stats file",
|
||||
"metadata/table.stats",
|
||||
},
|
||||
{
|
||||
"puffin statistics file",
|
||||
"metadata/20260928-1-0199a3c2-7d1e-7c55-9a0e-3b1f2c4d5e6f.puffin",
|
||||
},
|
||||
}
|
||||
|
||||
v := NewIcebergLayoutValidator()
|
||||
@@ -70,6 +74,8 @@ func TestIcebergLayoutValidator_RejectsClearlyBadMetadataNames(t *testing.T) {
|
||||
{"subdirectory under metadata is not allowed", "metadata/sub/file.avro"},
|
||||
{"top-level dir other than metadata or data", "garbage/file.avro"},
|
||||
{"catch-all anchors must reject trailing extension", "metadata/file.avro.txt"},
|
||||
{"puffin with a trailing extension", "metadata/stats.puffin.txt"},
|
||||
{"puffin in a subdirectory under metadata", "metadata/sub/stats.puffin"},
|
||||
}
|
||||
|
||||
v := NewIcebergLayoutValidator()
|
||||
@@ -137,3 +143,31 @@ func TestValidateFilePathAcceptsLanceLayout(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Statistics files are referenced from the table metadata and kept by orphan
|
||||
// cleanup; the upload door has to admit them in the table's metadata/, and
|
||||
// only there.
|
||||
func TestTableBucketFileValidator_PuffinStatisticsOnlyInTableMetadata(t *testing.T) {
|
||||
v := NewTableBucketFileValidator()
|
||||
accepted := []string{
|
||||
TablesPath + "/cat/ns/t/metadata/stats-1.puffin",
|
||||
TablesPath + "/cat/ns/t/metadata/table.stats",
|
||||
TablesPath + "/cat/ns/t/data/0199a3c2-deletes.puffin",
|
||||
}
|
||||
for _, p := range accepted {
|
||||
if err := v.ValidateTableBucketUpload(p); err != nil {
|
||||
t.Errorf("ValidateTableBucketUpload(%q) = %v, want nil", p, err)
|
||||
}
|
||||
}
|
||||
rejected := []string{
|
||||
TablesPath + "/cat/ns/t/stats-1.puffin",
|
||||
TablesPath + "/cat/ns/t/other/stats-1.puffin",
|
||||
TablesPath + "/cat/ns/t/metadata/sub/stats-1.puffin",
|
||||
TablesPath + "/cat/ns/t/metadata/notes.txt",
|
||||
}
|
||||
for _, p := range rejected {
|
||||
if err := v.ValidateTableBucketUpload(p); err == nil {
|
||||
t.Errorf("ValidateTableBucketUpload(%q) = nil, want an error", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user