mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63c218c399 | ||
|
|
3b4690d1b7 | ||
|
|
9a7f033d7f |
No files matched your search
@@ -740,11 +740,7 @@ impl DiskLocation {
|
||||
if vol.is_read_only() {
|
||||
continue;
|
||||
}
|
||||
// A preallocated volume already holds its space on disk.
|
||||
let dat_size = vol
|
||||
.dat_file_size()
|
||||
.unwrap_or(0)
|
||||
.max(vol.dat_allocated_size());
|
||||
let dat_size = vol.dat_file_size().unwrap_or(0);
|
||||
let idx_size = vol.idx_file_size();
|
||||
let used = dat_size + idx_size;
|
||||
if volume_size_limit > used {
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::storage::erasure_coding::ec_volume::{
|
||||
};
|
||||
use crate::storage::needle::needle::{Needle, get_actual_size};
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::super_block::{ReplicaPlacement, SUPER_BLOCK_SIZE, SuperBlock};
|
||||
use crate::storage::super_block::{ReplicaPlacement, SUPER_BLOCK_SIZE};
|
||||
use crate::storage::types::*;
|
||||
use crate::storage::volume::{CompactionJob, VifVolumeInfo, Volume, VolumeError, VolumeSpec};
|
||||
|
||||
@@ -762,8 +762,8 @@ impl Store {
|
||||
}
|
||||
|
||||
/// Configure a volume's replica placement on disk.
|
||||
/// The volume must already be unmounted. Rewrites the .vif and the .dat
|
||||
/// superblock so both carry the new placement.
|
||||
/// The volume must already be unmounted. This opens the .dat file directly,
|
||||
/// modifies the replica_placement byte (offset 1), and writes it back.
|
||||
pub fn configure_volume(&self, vid: VolumeId, rp: ReplicaPlacement) -> Result<(), VolumeError> {
|
||||
let (_, base_path, _) = self.find_volume_file_base(vid).ok_or_else(|| {
|
||||
VolumeError::Io(io::Error::new(
|
||||
@@ -775,7 +775,7 @@ impl Store {
|
||||
let mut vif = load_vif_volume_info(&vif_path)?;
|
||||
vif.replication = rp.to_string();
|
||||
save_vif_volume_info(&vif_path, &vif)?;
|
||||
update_dat_replica_placement(&format!("{}.dat", base_path), vid, rp)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- Read / Write / Delete ----
|
||||
@@ -943,7 +943,11 @@ impl Store {
|
||||
let current = loc.max_volume_count.load(Ordering::Relaxed);
|
||||
let (_, free) = super::disk_location::get_disk_stats(&loc.directory);
|
||||
|
||||
let unused_space = loc.unused_space(volume_size_limit);
|
||||
let unused_space = if self.get_preallocate() {
|
||||
0
|
||||
} else {
|
||||
loc.unused_space(volume_size_limit)
|
||||
};
|
||||
let unclaimed = (free as i64) - (unused_space as i64);
|
||||
|
||||
let vol_count = loc.volumes_len() as i32;
|
||||
@@ -1740,61 +1744,6 @@ fn strip_volume_suffix(filename: &str) -> Option<&str> {
|
||||
.or_else(|| filename.strip_suffix(".idx"))
|
||||
}
|
||||
|
||||
/// Rewrites the replica placement in a .dat header for a volume that is not
|
||||
/// mounted; a missing .dat means a remote-only volume, where the .vif carries
|
||||
/// the placement.
|
||||
fn update_dat_replica_placement(
|
||||
dat_path: &str,
|
||||
vid: VolumeId,
|
||||
rp: ReplicaPlacement,
|
||||
) -> Result<(), VolumeError> {
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
|
||||
let mut file = match std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(dat_path)
|
||||
{
|
||||
Ok(f) => f,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(e) => {
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
e.kind(),
|
||||
format!("volume {} failed to open {}: {}", vid, dat_path, e),
|
||||
)))
|
||||
}
|
||||
};
|
||||
let mut header = [0u8; SUPER_BLOCK_SIZE];
|
||||
file.read_exact(&mut header).map_err(|e| {
|
||||
VolumeError::Io(io::Error::new(
|
||||
e.kind(),
|
||||
format!("volume {} failed to parse superblock: {}", vid, e),
|
||||
))
|
||||
})?;
|
||||
let extra_size = u16::from_be_bytes([header[6], header[7]]) as usize;
|
||||
let mut block = header.to_vec();
|
||||
block.resize(SUPER_BLOCK_SIZE + extra_size, 0);
|
||||
if extra_size > 0 {
|
||||
file.read_exact(&mut block[SUPER_BLOCK_SIZE..]).map_err(|e| {
|
||||
VolumeError::Io(io::Error::new(
|
||||
e.kind(),
|
||||
format!("volume {} failed to parse superblock: {}", vid, e),
|
||||
))
|
||||
})?;
|
||||
}
|
||||
let mut super_block = SuperBlock::from_bytes(&block).map_err(|e| {
|
||||
VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("volume {} failed to parse superblock: {}", vid, e),
|
||||
))
|
||||
})?;
|
||||
super_block.replica_placement = rp;
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
file.write_all(&super_block.to_bytes())?;
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_vif_volume_info(path: &str) -> Result<VifVolumeInfo, VolumeError> {
|
||||
let content = match std::fs::read_to_string(path) {
|
||||
Ok(c) => c,
|
||||
@@ -2032,33 +1981,6 @@ mod tests {
|
||||
assert_eq!(store.total_volume_count(), 1);
|
||||
}
|
||||
|
||||
// Mirrors Go's TestConfigureVolumeUpdatesSuperblock: configure must leave
|
||||
// the .dat header and the .vif both on the new placement.
|
||||
#[test]
|
||||
fn test_configure_volume_updates_superblock() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut store = make_test_store(&[dir]);
|
||||
|
||||
store
|
||||
.add_volume(VolumeId(1), DiskType::HardDrive, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
assert!(store.unmount_volume(VolumeId(1)).unwrap());
|
||||
|
||||
let rp = ReplicaPlacement::from_string("010").unwrap();
|
||||
store.configure_volume(VolumeId(1), rp).unwrap();
|
||||
|
||||
let base = volume_file_name(dir, "", VolumeId(1));
|
||||
let vif = load_vif_volume_info(&format!("{}.vif", base)).unwrap();
|
||||
assert_eq!(vif.replication, "010");
|
||||
|
||||
let dat = std::fs::read(format!("{}.dat", base)).unwrap();
|
||||
let super_block = SuperBlock::from_bytes(&dat).unwrap();
|
||||
assert_eq!(super_block.replica_placement, rp);
|
||||
|
||||
assert!(store.configure_volume(VolumeId(2), rp).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mount_volume_by_id_hint_skips_lone_sidecar() {
|
||||
// A lone .vif/.idx sidecar (e.g. an EC sidecar whose .ecx is on a
|
||||
@@ -2557,7 +2479,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_maybe_adjust_volume_max_reserves_plain_volumes_while_preallocating() {
|
||||
fn test_maybe_adjust_volume_max_honors_preallocate_flag() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
|
||||
@@ -2572,6 +2494,13 @@ mod tests {
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
// Use a large volume_size_limit so the unused-space difference between
|
||||
// preallocate=true (0) and preallocate=false (~2 × limit) is big enough
|
||||
// that integer-division rounding and disk-free fluctuations between the
|
||||
// two get_disk_stats calls cannot make the quotients equal.
|
||||
store
|
||||
.volume_size_limit
|
||||
.store(100 * 1024 * 1024, Ordering::Relaxed);
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(61),
|
||||
@@ -2582,67 +2511,39 @@ mod tests {
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Room for 2.5 volumes: the plain volume claims one, leaving one more slot.
|
||||
let (_, free) = crate::storage::disk_location::get_disk_stats(dir);
|
||||
let volume_size_limit = (free as f64 / 2.5) as u64;
|
||||
if volume_size_limit == 0 {
|
||||
return; // cannot determine free disk space
|
||||
}
|
||||
store
|
||||
.volume_size_limit
|
||||
.store(volume_size_limit, Ordering::Relaxed);
|
||||
store.locations[0].original_max_volume_count = 0;
|
||||
store.set_preallocate(true);
|
||||
|
||||
store.maybe_adjust_volume_max();
|
||||
assert_eq!(
|
||||
store.locations[0].max_volume_count.load(Ordering::Relaxed),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_unused_space_counts_preallocated_volumes_as_full() {
|
||||
const LIMIT: u64 = 1 << 20;
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
2,
|
||||
.add_volume(
|
||||
VolumeId(62),
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
&VolumeSpec {
|
||||
collection: "preallocate_case",
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
for (vid, preallocate) in [(VolumeId(71), LIMIT), (VolumeId(72), 0)] {
|
||||
store
|
||||
.add_volume(
|
||||
vid,
|
||||
DiskType::HardDrive,
|
||||
&VolumeSpec {
|
||||
collection: "preallocate_case",
|
||||
preallocate,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
for vid in [VolumeId(61), VolumeId(62)] {
|
||||
let dat_path = store.find_volume(vid).unwrap().1.dat_path();
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(dat_path)
|
||||
.unwrap()
|
||||
.set_len((crate::storage::super_block::SUPER_BLOCK_SIZE + 1) as u64)
|
||||
.unwrap();
|
||||
}
|
||||
let preallocated = store.find_volume(VolumeId(71)).unwrap().1;
|
||||
if preallocated.dat_allocated_size() < LIMIT {
|
||||
return; // the filesystem does not support fallocate
|
||||
}
|
||||
store.locations[0].original_max_volume_count = 0;
|
||||
store.locations[0]
|
||||
.max_volume_count
|
||||
.store(0, Ordering::Relaxed);
|
||||
|
||||
let plain = store.find_volume(VolumeId(72)).unwrap().1;
|
||||
let plain_dat = plain.dat_file_size().unwrap();
|
||||
// The filesystem may round a small file up to a larger allocation unit.
|
||||
let plain_used = plain_dat.max(plain.dat_allocated_size()) + plain.idx_file_size();
|
||||
assert_eq!(store.locations[0].unused_space(LIMIT), LIMIT - plain_used);
|
||||
store.set_preallocate(false);
|
||||
assert!(store.maybe_adjust_volume_max());
|
||||
let without_preallocate = store.locations[0].max_volume_count.load(Ordering::Relaxed);
|
||||
|
||||
store.set_preallocate(true);
|
||||
assert!(store.maybe_adjust_volume_max());
|
||||
let with_preallocate = store.locations[0].max_volume_count.load(Ordering::Relaxed);
|
||||
|
||||
assert!(with_preallocate > without_preallocate);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4185,10 +4185,8 @@ impl Volume {
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let (was_no_write_or_delete, was_no_write_can_delete) = self.no_write_flags();
|
||||
// A remote-tiered volume keeps the delete-only mode a load derives: its
|
||||
// .dat cannot take appends, so "writable" resolves to can-delete rather
|
||||
// than advertising writable with no local data file.
|
||||
let no_write_can_delete = self.has_remote_file();
|
||||
// Remote-tiered volumes must stay no_write_can_delete regardless of marks.
|
||||
let no_write_can_delete = was_no_write_can_delete && self.has_remote_file();
|
||||
self.no_write.store(
|
||||
if no_write_can_delete {
|
||||
NO_WRITE_CAN_DELETE
|
||||
@@ -4302,70 +4300,21 @@ impl Volume {
|
||||
}
|
||||
f(&mut self.volume_info.write().unwrap().files);
|
||||
let mut io = self.io.write().unwrap();
|
||||
self.refresh_remote_write_mode(&mut io, true)
|
||||
}
|
||||
|
||||
/// Go's MarkTieredDeletable: a live tier-up lifts the upload-time
|
||||
/// read-only mark, except on a replicated volume — the shell copies the
|
||||
/// uploaded replica's .idx and .vif to the other replicas after the
|
||||
/// upload, and a tombstone written before that copy would reach one
|
||||
/// replica only — or under an I/O quarantine, which is not the tier
|
||||
/// upload's to lift. A refused volume keeps its flags until the next
|
||||
/// load, as the Go volume does.
|
||||
fn mark_tiered_deletable(&self) -> bool {
|
||||
if self
|
||||
.super_block
|
||||
.read()
|
||||
.unwrap()
|
||||
.replica_placement
|
||||
.has_replication()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if !self.has_remote_file() {
|
||||
return false;
|
||||
}
|
||||
// Go takes noWriteLock around the quarantine check and the flag
|
||||
// change; here a compare-exchange gives the same ordering — a
|
||||
// heartbeat refusal landing between the check and the swap fails the
|
||||
// swap, and the retry sees the quarantine mark the heartbeat set
|
||||
// first.
|
||||
loop {
|
||||
if self.should_quarantine() {
|
||||
return false;
|
||||
}
|
||||
let flags = self.no_write.load(Ordering::Acquire);
|
||||
let promoted = (flags & !NO_WRITE_OR_DELETE) | NO_WRITE_CAN_DELETE;
|
||||
if self
|
||||
.no_write
|
||||
.compare_exchange(flags, promoted, Ordering::AcqRel, Ordering::Acquire)
|
||||
.is_ok()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
self.refresh_remote_write_mode(&mut io)
|
||||
}
|
||||
|
||||
/// Recompute the Go-style write/delete mode from the current remote tier
|
||||
/// state, and bring the needle map in line with it — a volume that stops
|
||||
/// being remote also stops using the read-only sorted index.
|
||||
///
|
||||
/// `live` is a tier transition on a running volume: the promotion then
|
||||
/// goes through mark_tiered_deletable, Go's MarkTieredDeletable, while a
|
||||
/// load promotes every tiered volume unconditionally as Go's load() does.
|
||||
///
|
||||
/// If the map cannot be rebuilt the volume is pinned read-only rather than
|
||||
/// published as writable with an index that rejects every put; a restart
|
||||
/// recovers it.
|
||||
fn refresh_remote_write_mode(&self, io: &mut VolumeIo, live: bool) -> Result<(), VolumeError> {
|
||||
fn refresh_remote_write_mode(&self, io: &mut VolumeIo) -> Result<(), VolumeError> {
|
||||
let has_remote = self.has_remote_file();
|
||||
if has_remote {
|
||||
// remote-tiered: no writes, deletes allowed
|
||||
if !live {
|
||||
self.no_write.store(NO_WRITE_CAN_DELETE, Ordering::Release);
|
||||
} else {
|
||||
self.mark_tiered_deletable();
|
||||
}
|
||||
self.no_write.store(NO_WRITE_CAN_DELETE, Ordering::Release);
|
||||
} else if !self.volume_info.read().unwrap().read_only_can_delete {
|
||||
// only clear the remoteness-derived flag, not an operator mark
|
||||
self.set_no_write_flag(NO_WRITE_CAN_DELETE, false);
|
||||
@@ -4414,7 +4363,7 @@ impl Volume {
|
||||
}
|
||||
}
|
||||
*self.volume_info.write().unwrap() = pb_info;
|
||||
self.refresh_remote_write_mode(io, false)?;
|
||||
self.refresh_remote_write_mode(io)?;
|
||||
{
|
||||
let mut vi = self.volume_info.write().unwrap();
|
||||
if vi.version == 0 {
|
||||
@@ -4445,7 +4394,7 @@ impl Volume {
|
||||
self.set_no_write_flag(NO_WRITE_OR_DELETE, true);
|
||||
}
|
||||
*self.volume_info.write().unwrap() = pb_info;
|
||||
self.refresh_remote_write_mode(io, false)?;
|
||||
self.refresh_remote_write_mode(io)?;
|
||||
{
|
||||
let mut vi = self.volume_info.write().unwrap();
|
||||
if vi.version == 0 {
|
||||
@@ -4985,25 +4934,6 @@ impl Volume {
|
||||
self.current_dat_file_size()
|
||||
}
|
||||
|
||||
/// Disk space held by the local .dat file, or 0 when it is unknown. It
|
||||
/// exceeds the file size when the file was preallocated with
|
||||
/// `FALLOC_FL_KEEP_SIZE`.
|
||||
pub fn dat_allocated_size(&self) -> u64 {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let io = self.io.read().unwrap();
|
||||
io.dat_file
|
||||
.as_ref()
|
||||
.and_then(|f| f.metadata().ok())
|
||||
.map_or(0, |m| m.blocks() * 512)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the modification time of the .dat file as Unix seconds.
|
||||
pub fn dat_file_mod_time(&self) -> u64 {
|
||||
let io = self.io.read().unwrap();
|
||||
@@ -9771,72 +9701,6 @@ mod tests {
|
||||
assert!(!v.is_no_write_or_delete());
|
||||
}
|
||||
|
||||
/// Go's MarkTieredDeletable leaves a replicated volume's upload-time
|
||||
/// read-only mark alone: the shell still has to copy the uploaded
|
||||
/// replica's .idx to the others, and a tombstone written before that copy
|
||||
/// would reach one replica only.
|
||||
#[test]
|
||||
fn test_update_remote_files_keeps_a_replicated_volume_refusing_deletes() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
v.super_block.write().unwrap().replica_placement =
|
||||
crate::storage::super_block::ReplicaPlacement::from_string("001").unwrap();
|
||||
v.set_no_write_or_delete(true); // the shell's pre-upload mark
|
||||
|
||||
v.update_remote_files(|files| files.push(Default::default()))
|
||||
.unwrap();
|
||||
|
||||
assert!(v.has_remote_file());
|
||||
assert!(
|
||||
v.is_no_write_or_delete(),
|
||||
"a replicated volume keeps refusing deletes until its next load"
|
||||
);
|
||||
assert!(!v.is_no_write_can_delete());
|
||||
}
|
||||
|
||||
/// An I/O quarantine is not the tier upload's to lift: a live tier-up
|
||||
/// leaves a quarantined volume's read-only mark alone, as Go's
|
||||
/// MarkTieredDeletable does.
|
||||
#[test]
|
||||
fn test_update_remote_files_keeps_an_io_quarantine() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
v.set_no_write_or_delete(true);
|
||||
v.mark_io_quarantined();
|
||||
|
||||
v.update_remote_files(|files| files.push(Default::default()))
|
||||
.unwrap();
|
||||
|
||||
assert!(v.has_remote_file());
|
||||
assert!(v.is_no_write_or_delete());
|
||||
assert!(!v.is_no_write_can_delete());
|
||||
}
|
||||
|
||||
/// A refused tiered volume keeps OR_DELETE without CAN_DELETE; marking it
|
||||
/// writable must resolve to the delete-only mode a load derives — the
|
||||
/// remote .dat cannot take appends — not drop every protection.
|
||||
#[test]
|
||||
fn test_set_writable_on_a_refused_tiered_volume_stays_delete_only() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
v.super_block.write().unwrap().replica_placement =
|
||||
crate::storage::super_block::ReplicaPlacement::from_string("001").unwrap();
|
||||
v.set_no_write_or_delete(true);
|
||||
|
||||
v.update_remote_files(|files| files.push(Default::default()))
|
||||
.unwrap();
|
||||
assert!(v.is_no_write_or_delete());
|
||||
|
||||
v.set_writable().unwrap();
|
||||
|
||||
assert!(v.is_read_only());
|
||||
assert!(!v.no_write_flags().0);
|
||||
assert!(v.no_write_flags().1);
|
||||
}
|
||||
|
||||
// Tier-down clears the remote mode and publishes the volume as writable. The
|
||||
// map it booted with is the read-only sorted one, whose put always fails, so
|
||||
// without a rebuild the first write appends to .dat and then cannot be
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
package s3tables
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/config"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/smithy-go"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newObjectClient(t *testing.T) *s3.Client {
|
||||
t.Helper()
|
||||
cfg, err := config.LoadDefaultConfig(context.Background(),
|
||||
config.WithRegion(testRegion),
|
||||
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(testAccessKey, testSecretKey, "")),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return s3.NewFromConfig(cfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(sharedCluster.s3Endpoint)
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
}
|
||||
|
||||
func apiErrorCode(err error) string {
|
||||
var apiErr smithy.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
return apiErr.ErrorCode()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// The external-volume verification object round-trips at a table bucket's
|
||||
// root the way the check uses it: PUT, HEAD, GET, list, DELETE. Any other key
|
||||
// at the root is still refused.
|
||||
func TestTableBucketExternalVolumeVerificationRoundTrip(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
ctx := context.Background()
|
||||
tables := NewS3TablesClient(sharedCluster.s3Endpoint, testRegion, testAccessKey, testSecretKey)
|
||||
bucket := "verify-" + randomString(8)
|
||||
created, err := tables.CreateTableBucket(bucket, nil)
|
||||
require.NoError(t, err)
|
||||
defer tables.DeleteTableBucket(created.ARN)
|
||||
client := newObjectClient(t)
|
||||
|
||||
body := []byte("verification payload!") // 21 bytes
|
||||
key := fmt.Sprintf("verify_%d_%d", time.Now().UnixMilli(), 1081846483)
|
||||
|
||||
// the control: an ordinary key at the root is refused
|
||||
_, err = client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String("notes.parquet"), Body: bytes.NewReader(body)})
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, "AccessDenied", apiErrorCode(err))
|
||||
|
||||
_, err = client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String(key), Body: bytes.NewReader(body), ContentLength: aws.Int64(int64(len(body)))})
|
||||
require.NoError(t, err)
|
||||
|
||||
head, err := client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(len(body)), aws.ToInt64(head.ContentLength))
|
||||
|
||||
got, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
data, err := io.ReadAll(got.Body)
|
||||
got.Body.Close()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, body, data)
|
||||
|
||||
list, err := client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: aws.String(bucket), Prefix: aws.String("verify_")})
|
||||
require.NoError(t, err)
|
||||
var keys []string
|
||||
for _, o := range list.Contents {
|
||||
keys = append(keys, aws.ToString(o.Key))
|
||||
}
|
||||
assert.Equal(t, []string{key}, keys)
|
||||
|
||||
_, err = client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
_, err = client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.Error(t, err, "the verification object must be gone after DELETE")
|
||||
}
|
||||
|
||||
// A namespace can carry a name of the verification key's shape. The key
|
||||
// then names the namespace's directory: a PUT or DELETE through it must not
|
||||
// replace or remove the namespace.
|
||||
func TestTableBucketVerificationKeyLeavesNamespaceAlone(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
ctx := context.Background()
|
||||
tables := NewS3TablesClient(sharedCluster.s3Endpoint, testRegion, testAccessKey, testSecretKey)
|
||||
bucket := "verify-ns-" + randomString(8)
|
||||
created, err := tables.CreateTableBucket(bucket, nil)
|
||||
require.NoError(t, err)
|
||||
defer tables.DeleteTableBucket(created.ARN)
|
||||
client := newObjectClient(t)
|
||||
body := []byte("verification payload!")
|
||||
|
||||
listed := func(name string) bool {
|
||||
resp, err := tables.ListNamespaces(created.ARN, "", "", 0)
|
||||
require.NoError(t, err)
|
||||
for _, ns := range resp.Namespaces {
|
||||
if len(ns.Namespace) == 1 && ns.Namespace[0] == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
for i, op := range []string{"PUT", "DELETE"} {
|
||||
t.Run(op, func(t *testing.T) {
|
||||
name := fmt.Sprintf("verify_%d_%d", time.Now().UnixMilli(), 7+i)
|
||||
_, err := tables.CreateNamespace(created.ARN, []string{name})
|
||||
require.NoError(t, err)
|
||||
defer tables.DeleteNamespace(created.ARN, []string{name})
|
||||
require.True(t, listed(name), "setup: the namespace is listed")
|
||||
|
||||
if op == "PUT" {
|
||||
_, err = client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String(name), Body: bytes.NewReader(body), ContentLength: aws.Int64(int64(len(body)))})
|
||||
assert.Error(t, err, "a PUT over a namespace must be refused")
|
||||
} else {
|
||||
_, err = client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(name)})
|
||||
assert.Error(t, err, "a DELETE of a namespace must be refused")
|
||||
}
|
||||
_, err = tables.GetNamespace(created.ARN, []string{name})
|
||||
assert.NoError(t, err, "the namespace survives the %s", op)
|
||||
assert.True(t, listed(name), "the namespace is still listed after the %s", op)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -51,15 +51,6 @@ var (
|
||||
// S3 gateway, whose remote-mount read paths dial the mounted endpoint directly.
|
||||
const allowUntrustedRemoteEndpointsUsage = "if true, a read of a remote-only entry accepts arbitrary remote S3 endpoints including loopback / link-local hosts. Default rejects internal / metadata endpoints."
|
||||
|
||||
// iamSelfServiceRequiresGrantUsage documents the flag shared by every command
|
||||
// that runs the embedded IAM API.
|
||||
const iamSelfServiceRequiresGrantUsage = "if true, an identity needs an explicit iam: grant to manage its own access keys (CreateAccessKey, DeleteAccessKey, UpdateAccessKey, ListAccessKeys, GetUser), as on AWS. Default allows it to every authenticated identity."
|
||||
|
||||
// allowBackslashInKeyUsage documents the S3 flag keeping '\' a literal
|
||||
// object-key character instead of normalizing it to '/'. Repeated '//' in a
|
||||
// key still collapses: a filer entry name cannot contain an empty segment.
|
||||
const allowBackslashInKeyUsage = "treat backslash as a regular object-key character instead of converting it to '/' (aws-compatible; '//' still collapses)"
|
||||
|
||||
type FilerOptions struct {
|
||||
masters *pb.ServerDiscovery
|
||||
mastersString *string
|
||||
@@ -182,8 +173,6 @@ func init() {
|
||||
filerS3Options.cacheSizeMB = cmdFiler.Flag.Int64("s3.cacheCapacityMB", 0, "in-memory chunk cache capacity in MB for S3 GETs shared across requests (0 disables)")
|
||||
filerS3Options.readerCacheSizeMB = cmdFiler.Flag.Int64("s3.readerCacheSizeMB", 0, "memory budget in MiB for downloaded and in-flight reader buffers across all S3 GETs (0 means unlimited)")
|
||||
filerS3Options.allowUntrustedRemoteEndpoints = cmdFiler.Flag.Bool("s3.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage)
|
||||
filerS3Options.allowBackslashInKey = cmdFiler.Flag.Bool("s3.allowBackslashInKey", false, allowBackslashInKeyUsage)
|
||||
filerS3Options.iamSelfServiceRequiresGrant = cmdFiler.Flag.Bool("s3.iam.selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage)
|
||||
|
||||
// start webdav on filer
|
||||
filerStartWebDav = cmdFiler.Flag.Bool("webdav", false, "whether to start webdav gateway")
|
||||
@@ -202,7 +191,6 @@ func init() {
|
||||
filerStartIam = cmdFiler.Flag.Bool("iam", false, "whether to start IAM service")
|
||||
filerIamOptions.ip = cmdFiler.Flag.String("iam.ip", *f.ip, "iam server http listen ip address")
|
||||
filerIamOptions.port = cmdFiler.Flag.Int("iam.port", 8111, "iam server http listen port")
|
||||
filerIamOptions.selfServiceRequiresGrant = filerS3Options.iamSelfServiceRequiresGrant
|
||||
|
||||
filerStartSftp = cmdFiler.Flag.Bool("sftp", false, "whether to start the SFTP server")
|
||||
filerSftpOptions.port = cmdFiler.Flag.Int("sftp.port", 2022, "SFTP server listen port")
|
||||
|
||||
@@ -140,17 +140,59 @@ func (option *RemoteSyncOptions) makeEventProcessor(remoteStorage *remote_pb.Rem
|
||||
if filer_pb.IsEmpty(resp) {
|
||||
return nil
|
||||
}
|
||||
renamedIntoMount := false
|
||||
if message.OldEntry != nil && message.NewEntry != nil {
|
||||
reshaped, inMount := reshapeCrossMountRename(mountedDir, resp)
|
||||
if !inMount {
|
||||
if filer_pb.IsCreate(resp) {
|
||||
if isMultipartUploadFile(message.NewParentPath, message.NewEntry.Name) {
|
||||
return nil
|
||||
}
|
||||
renamedIntoMount = reshaped != resp && filer_pb.IsCreate(reshaped)
|
||||
resp, message = reshaped, reshaped.EventNotification
|
||||
}
|
||||
if filer_pb.IsCreate(resp) {
|
||||
return processCreateEvent(option, filerSource, *option.storageClass, client, mountedDir, remoteStorageMountLocation, resp, renamedIntoMount)
|
||||
// Propagate delete markers as deletions on the remote.
|
||||
// Delete markers are zero-content version entries, so they
|
||||
// would be filtered out by the HasData check below.
|
||||
if isDeleteMarker(message.NewEntry) {
|
||||
if newParent, newName, ok := rewriteVersionedSourcePath(message.NewParentPath, message.NewEntry.Name); ok {
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(newParent, newName), remoteStorageMountLocation)
|
||||
return syncDeleteMarker(client, option, message, dest)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !filer.HasData(message.NewEntry) {
|
||||
return nil
|
||||
}
|
||||
glog.V(2).Infof("create: %+v", resp)
|
||||
if !shouldSendToRemote(message.NewEntry) {
|
||||
glog.V(2).Infof("skipping creating: %+v", resp)
|
||||
return nil
|
||||
}
|
||||
// Rewrite internal versioning paths to the original S3 key
|
||||
// to prevent double-versioning when central also has versioning enabled
|
||||
parentPath, entryName := message.NewParentPath, message.NewEntry.Name
|
||||
isRewrittenVersion := false
|
||||
if newParent, newName, ok := rewriteVersionedSourcePath(parentPath, entryName); ok {
|
||||
glog.V(0).Infof("rewrite versioned path %s/%s -> %s/%s", parentPath, entryName, newParent, newName)
|
||||
parentPath, entryName = newParent, newName
|
||||
isRewrittenVersion = true
|
||||
}
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(parentPath, entryName), remoteStorageMountLocation)
|
||||
if message.NewEntry.IsDirectory {
|
||||
glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
|
||||
return client.WriteDirectory(dest, remoteWriteEntry(message.NewEntry, *option.storageClass))
|
||||
}
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, remoteWriteEntry(message.NewEntry, *option.storageClass), dest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
|
||||
return nil
|
||||
}
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
// Skip updateLocalEntry for versioned rewrites: the logical
|
||||
// object (e.g. file.xml) has no filer entry in versioned
|
||||
// buckets, and stamping the internal v_* entry with a
|
||||
// RemoteEntry for the logical key is semantically wrong.
|
||||
// Replay is safe because S3 PutObject is idempotent.
|
||||
if isRewrittenVersion {
|
||||
return nil
|
||||
}
|
||||
return updateLocalEntry(option, message.NewParentPath, message.NewEntry, remoteEntry)
|
||||
}
|
||||
if filer_pb.IsDelete(resp) {
|
||||
return processDeleteEvent(filerSource, client, mountedDir, remoteStorageMountLocation, resp)
|
||||
@@ -164,125 +206,6 @@ func (option *RemoteSyncOptions) makeEventProcessor(remoteStorage *remote_pb.Rem
|
||||
return eachEntryFunc, nil
|
||||
}
|
||||
|
||||
// reshapeCrossMountRename maps an update event onto the side of it the mount
|
||||
// covers. The subscription delivers a rename when either of its paths lies
|
||||
// under the mounted directory, and only a path under it maps to a remote
|
||||
// key: toRemoteStorageLocation slices the mount prefix off, which panics on
|
||||
// a shorter path and names a key in the wrong tree on a longer one. A rename
|
||||
// into the mount is the creation of the new entry, a rename out of it the
|
||||
// deletion of the old entry's object, unless that entry is remote-only and
|
||||
// the object holds its only copy. An update with both paths inside is
|
||||
// returned as is; one with neither is not the mount's (false).
|
||||
func reshapeCrossMountRename(mountedDir string, resp *filer_pb.SubscribeMetadataResponse) (*filer_pb.SubscribeMetadataResponse, bool) {
|
||||
message := resp.EventNotification
|
||||
oldInMount := isUnderMount(mountedDir, resp.Directory, message.OldEntry.Name)
|
||||
newInMount := isUnderMount(mountedDir, message.NewParentPath, message.NewEntry.Name)
|
||||
switch {
|
||||
case oldInMount && newInMount:
|
||||
return resp, true
|
||||
case newInMount:
|
||||
glog.V(0).Infof("rename into mount %s: %s/%s -> %s/%s, creating", mountedDir, resp.Directory, message.OldEntry.Name, message.NewParentPath, message.NewEntry.Name)
|
||||
return &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: message.NewParentPath,
|
||||
EventNotification: &filer_pb.EventNotification{NewEntry: message.NewEntry, NewParentPath: message.NewParentPath, Signatures: message.Signatures},
|
||||
TsNs: resp.TsNs,
|
||||
}, true
|
||||
case oldInMount:
|
||||
if isRemoteOnly(message.OldEntry) {
|
||||
glog.V(0).Infof("rename out of mount %s: %s/%s -> %s/%s, keeping the remote-only object", mountedDir, resp.Directory, message.OldEntry.Name, message.NewParentPath, message.NewEntry.Name)
|
||||
return nil, false
|
||||
}
|
||||
glog.V(0).Infof("rename out of mount %s: %s/%s -> %s/%s, deleting", mountedDir, resp.Directory, message.OldEntry.Name, message.NewParentPath, message.NewEntry.Name)
|
||||
return &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: resp.Directory,
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: message.OldEntry, Signatures: message.Signatures},
|
||||
TsNs: resp.TsNs,
|
||||
}, true
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// isUnderMount reports whether dir/name is the mounted directory or lies
|
||||
// below it; a trailing slash on the mount flag does not change the answer.
|
||||
func isUnderMount(mountedDir string, dir string, name string) bool {
|
||||
mount := strings.TrimSuffix(mountedDir, "/")
|
||||
path := string(util.NewFullPath(dir, name))
|
||||
return path == mount || strings.HasPrefix(path, mount+"/")
|
||||
}
|
||||
|
||||
// processCreateEvent uploads a created entry to the remote key its path maps
|
||||
// to. A create reshaped from a rename into the mount (renamedIntoMount) writes
|
||||
// whatever the entry holds: the stamp it inherited describes an object the
|
||||
// move out deleted, so it cannot skip the upload, and an empty file still
|
||||
// takes a zero-byte object. A remote-only entry still skips: it holds nothing
|
||||
// local to send, and the filer refuses to rename one out of its mount, so its
|
||||
// object remains under the key its path maps to.
|
||||
func processCreateEvent(
|
||||
filerClient filer_pb.FilerClient,
|
||||
filerSource filer_pb.FilerClient,
|
||||
storageClass string,
|
||||
client remote_storage.RemoteStorageClient,
|
||||
mountedDir string,
|
||||
remoteStorageMountLocation *remote_pb.RemoteStorageLocation,
|
||||
resp *filer_pb.SubscribeMetadataResponse,
|
||||
renamedIntoMount bool,
|
||||
) error {
|
||||
message := resp.EventNotification
|
||||
if isMultipartUploadFile(message.NewParentPath, message.NewEntry.Name) {
|
||||
return nil
|
||||
}
|
||||
// Propagate delete markers as deletions on the remote.
|
||||
// Delete markers are zero-content version entries, so they
|
||||
// would be filtered out by the HasData check below.
|
||||
if isDeleteMarker(message.NewEntry) {
|
||||
if newParent, newName, ok := rewriteVersionedSourcePath(message.NewParentPath, message.NewEntry.Name); ok {
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(newParent, newName), remoteStorageMountLocation)
|
||||
return syncDeleteMarker(client, filerClient, message, dest)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !filer.HasData(message.NewEntry) && !(renamedIntoMount && !isRemoteOnly(message.NewEntry)) {
|
||||
return nil
|
||||
}
|
||||
glog.V(2).Infof("create: %+v", resp)
|
||||
if !renamedIntoMount && !shouldSendToRemote(message.NewEntry) {
|
||||
glog.V(2).Infof("skipping creating: %+v", resp)
|
||||
return nil
|
||||
}
|
||||
// Rewrite internal versioning paths to the original S3 key
|
||||
// to prevent double-versioning when central also has versioning enabled
|
||||
parentPath, entryName := message.NewParentPath, message.NewEntry.Name
|
||||
isRewrittenVersion := false
|
||||
if newParent, newName, ok := rewriteVersionedSourcePath(parentPath, entryName); ok {
|
||||
glog.V(0).Infof("rewrite versioned path %s/%s -> %s/%s", parentPath, entryName, newParent, newName)
|
||||
parentPath, entryName = newParent, newName
|
||||
isRewrittenVersion = true
|
||||
}
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(parentPath, entryName), remoteStorageMountLocation)
|
||||
if message.NewEntry.IsDirectory {
|
||||
glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
|
||||
return client.WriteDirectory(dest, remoteWriteEntry(message.NewEntry, storageClass))
|
||||
}
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, remoteWriteEntry(message.NewEntry, storageClass), dest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
|
||||
return nil
|
||||
}
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
// Skip updateLocalEntry for versioned rewrites: the logical
|
||||
// object (e.g. file.xml) has no filer entry in versioned
|
||||
// buckets, and stamping the internal v_* entry with a
|
||||
// RemoteEntry for the logical key is semantically wrong.
|
||||
// Replay is safe because S3 PutObject is idempotent.
|
||||
if isRewrittenVersion {
|
||||
return nil
|
||||
}
|
||||
return updateLocalEntry(filerClient, message.NewParentPath, message.NewEntry, remoteEntry)
|
||||
}
|
||||
|
||||
// processDeleteEvent removes the remote object an entry mapped to. A remote
|
||||
// object that is already absent counts as deleted: the entry was never
|
||||
// uploaded (created and deleted faster than the sync ran, or a replay of an
|
||||
|
||||
@@ -2016,222 +2016,3 @@ func TestMetadataUpdateKeepsTheStoredStampOnNilResult(t *testing.T) {
|
||||
t.Fatalf("stamped RemoteEntry = %+v, want the entry's own stamp kept (mtime 100)", filerClient.updated.Entry.RemoteEntry)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReshapeCrossMountRename covers an update event with a path outside
|
||||
// the mount. The subscription delivers a rename when either path is under
|
||||
// the mount, and an update of the /etc/remote directory entry itself through
|
||||
// the daemon's /etc/remote prefix; processUpdateEvent then sliced the mount
|
||||
// prefix off both paths, which panics on a path shorter than the mount (seen
|
||||
// on a replay: "slice bounds out of range [20:11]" on the 11-byte
|
||||
// /etc/remote, every restart dying on the same event) and names a key in the
|
||||
// wrong tree on a longer one.
|
||||
func TestReshapeCrossMountRename(t *testing.T) {
|
||||
const mount = "/buckets/mount"
|
||||
chunked := func(name string) *filer_pb.Entry {
|
||||
return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669, FileSize: 7}, Chunks: []*filer_pb.FileChunk{{FileId: "3,01", Size: 7}}}
|
||||
}
|
||||
event := func(oldDir, oldName, newDir, newName string, oldEntry *filer_pb.Entry) *filer_pb.SubscribeMetadataResponse {
|
||||
if oldEntry == nil {
|
||||
oldEntry = chunked(oldName)
|
||||
}
|
||||
return &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: oldDir,
|
||||
TsNs: 42,
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: oldEntry, NewParentPath: newDir, NewEntry: chunked(newName), Signatures: []int32{7}},
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("into the mount from a shorter path is a create of the new entry", func(t *testing.T) {
|
||||
resp := event("/plain", "in.txt", mount+"/lock", "in.txt", nil)
|
||||
got, inMount := reshapeCrossMountRename(mount, resp)
|
||||
if !inMount || !filer_pb.IsCreate(got) {
|
||||
t.Fatalf("got %+v inMount=%v, want a create", got, inMount)
|
||||
}
|
||||
if got.Directory != mount+"/lock" || got.EventNotification.NewParentPath != mount+"/lock" || got.EventNotification.NewEntry.Name != "in.txt" {
|
||||
t.Errorf("create at %s/%s (dir %s), want %s/in.txt", got.EventNotification.NewParentPath, got.EventNotification.NewEntry.Name, got.Directory, mount+"/lock")
|
||||
}
|
||||
if got.TsNs != 42 || len(got.EventNotification.Signatures) != 1 {
|
||||
t.Errorf("timestamp and signatures must carry over: %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("into the mount from a longer path outside it is a create, not a key in the wrong tree", func(t *testing.T) {
|
||||
resp := event("/buckets/other/deeper/tree", "x.txt", mount, "x.txt", nil)
|
||||
got, inMount := reshapeCrossMountRename(mount, resp)
|
||||
if !inMount || !filer_pb.IsCreate(got) || got.EventNotification.NewParentPath != mount {
|
||||
t.Fatalf("got %+v inMount=%v, want a create under %s", got, inMount, mount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("out of the mount is a delete of the old entry", func(t *testing.T) {
|
||||
resp := event(mount+"/lock", "out.txt", "/plain", "out.txt", nil)
|
||||
got, inMount := reshapeCrossMountRename(mount, resp)
|
||||
if !inMount || !filer_pb.IsDelete(got) {
|
||||
t.Fatalf("got %+v inMount=%v, want a delete", got, inMount)
|
||||
}
|
||||
if got.Directory != mount+"/lock" || got.EventNotification.OldEntry.Name != "out.txt" {
|
||||
t.Errorf("delete of %s/%s, want %s/out.txt", got.Directory, got.EventNotification.OldEntry.Name, mount+"/lock")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("out of the mount keeps the object of a remote-only entry", func(t *testing.T) {
|
||||
remoteOnly := &filer_pb.Entry{Name: "out.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669, FileSize: 7}, RemoteEntry: &filer_pb.RemoteEntry{StorageName: "b2", RemoteSize: 7, RemoteMtime: 1786096669}}
|
||||
resp := event(mount+"/lock", "out.txt", "/plain", "out.txt", remoteOnly)
|
||||
if got, inMount := reshapeCrossMountRename(mount, resp); inMount || got != nil {
|
||||
t.Fatalf("got %+v inMount=%v, want the event dropped", got, inMount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("both paths inside is the update itself", func(t *testing.T) {
|
||||
resp := event(mount+"/a", "x.txt", mount+"/b", "y.txt", nil)
|
||||
if got, inMount := reshapeCrossMountRename(mount, resp); !inMount || got != resp {
|
||||
t.Fatalf("got %+v inMount=%v, want the same event", got, inMount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an update of the /etc/remote directory entry itself is not the mount's event", func(t *testing.T) {
|
||||
dirEntry := &filer_pb.Entry{Name: "remote", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}}
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/etc",
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: dirEntry, NewParentPath: "/etc", NewEntry: dirEntry},
|
||||
}
|
||||
if got, inMount := reshapeCrossMountRename("/buckets/c4x-storage", resp); inMount || got != nil {
|
||||
t.Fatalf("got %+v inMount=%v, want the event dropped", got, inMount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("neither path inside is not the mount's event", func(t *testing.T) {
|
||||
resp := event("/plain", "x.txt", "/buckets/mounted-not", "x.txt", nil)
|
||||
if got, inMount := reshapeCrossMountRename(mount, resp); inMount || got != nil {
|
||||
t.Fatalf("got %+v inMount=%v, want the event dropped", got, inMount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a trailing slash on the mount flag changes nothing", func(t *testing.T) {
|
||||
resp := event("/plain", "in.txt", mount, "in.txt", nil)
|
||||
if got, inMount := reshapeCrossMountRename(mount+"/", resp); !inMount || !filer_pb.IsCreate(got) {
|
||||
t.Fatalf("got %+v inMount=%v, want a create", got, inMount)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestRenameIntoMountUploadsDespiteTheOldStamp covers a file synced at a path
|
||||
// under the mount, renamed out (which deleted its remote object), and renamed
|
||||
// back in: the entry still carries the RemoteEntry the first sync stamped, so
|
||||
// shouldSendToRemote would skip the create the reshape made, leaving the new
|
||||
// key without an object. A reshaped create must send unconditionally.
|
||||
func TestRenameIntoMountUploadsDespiteTheOldStamp(t *testing.T) {
|
||||
const mountedDir = "/buckets/mount"
|
||||
mountLoc := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/"}
|
||||
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "b2", RemoteETag: "abc", RemoteSize: 7, RemoteMtime: 1786096669, LastLocalSyncTsNs: 1786096669*1e9 + 1}
|
||||
newEntry := &filer_pb.Entry{
|
||||
Name: "back.txt",
|
||||
Content: []byte("payload"),
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669},
|
||||
RemoteEntry: stamp,
|
||||
}
|
||||
resp, inMount := reshapeCrossMountRename(mountedDir, &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/plain",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: "back.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}, RemoteEntry: stamp},
|
||||
NewParentPath: mountedDir + "/lock",
|
||||
NewEntry: newEntry,
|
||||
},
|
||||
})
|
||||
if !inMount || !filer_pb.IsCreate(resp) {
|
||||
t.Fatalf("reshape = %+v inMount=%v, want a create", resp, inMount)
|
||||
}
|
||||
if shouldSendToRemote(resp.EventNotification.NewEntry) {
|
||||
t.Fatal("precondition: the stamp the rename carried should fail shouldSendToRemote")
|
||||
}
|
||||
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: newEntry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantWrite := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/lock/back.txt"}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], wantWrite) {
|
||||
t.Fatalf("writes = %+v, want the new key %s written", remote.writes, remote_storage.FormatLocation(wantWrite))
|
||||
}
|
||||
|
||||
// a plain create keeps trusting the stamp
|
||||
remote = &recordingRemote{}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want the stamped create skipped", remote.writes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRenameIntoMountCreateUploads covers what the reshape hands the create
|
||||
// path: a rename into the mount becomes a create, and that create cannot
|
||||
// trust the stamp or the missing content the entry carries. An empty file
|
||||
// still takes a zero-byte object on the remote; a remote-only entry holds
|
||||
// nothing local to send, so it still skips.
|
||||
func TestRenameIntoMountCreateUploads(t *testing.T) {
|
||||
const mountedDir = "/buckets/mount"
|
||||
mountLoc := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/"}
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "b2", RemoteETag: "abc", RemoteSize: 7, RemoteMtime: 1786096669, LastLocalSyncTsNs: 1786096669*1e9 + 1}
|
||||
|
||||
renameIn := func(entry *filer_pb.Entry) *filer_pb.SubscribeMetadataResponse {
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/data/staging",
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: entry, NewParentPath: mountedDir + "/lock", NewEntry: entry},
|
||||
}
|
||||
reshaped, inMount := reshapeCrossMountRename(mountedDir, resp)
|
||||
if !inMount || !filer_pb.IsCreate(reshaped) {
|
||||
t.Fatalf("reshape got %+v inMount=%v, want a create", reshaped, inMount)
|
||||
}
|
||||
return reshaped
|
||||
}
|
||||
want := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/lock/in.txt"}
|
||||
|
||||
t.Run("an empty entry writes a zero-byte object", func(t *testing.T) {
|
||||
entry := &filer_pb.Entry{Name: "in.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}}
|
||||
if filer.HasData(entry) {
|
||||
t.Fatal("precondition: an empty file carries no data")
|
||||
}
|
||||
remote := &recordingRemote{objects: map[string][]byte{}}
|
||||
filerClient := &stubFilerClient{entry: entry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn(entry), true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], want) {
|
||||
t.Errorf("writes = %+v, want the mounted key %s written", remote.writes, remote_storage.FormatLocation(want))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a remote-only entry still does not upload", func(t *testing.T) {
|
||||
entry := &filer_pb.Entry{Name: "in.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669, FileSize: 7}, RemoteEntry: stamp}
|
||||
if !isRemoteOnly(entry) {
|
||||
t.Fatal("precondition: entry should be remote-only")
|
||||
}
|
||||
remote := &recordingRemote{objects: map[string][]byte{}}
|
||||
filerClient := &stubFilerClient{entry: entry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn(entry), true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none: there is nothing local to send", remote.writes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an ordinary create keeps the stamp and data gates", func(t *testing.T) {
|
||||
empty := &filer_pb.Entry{Name: "in.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}}
|
||||
create := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: mountedDir + "/lock",
|
||||
EventNotification: &filer_pb.EventNotification{NewParentPath: mountedDir + "/lock", NewEntry: empty},
|
||||
}
|
||||
remote := &recordingRemote{objects: map[string][]byte{}}
|
||||
filerClient := &stubFilerClient{entry: empty}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, create, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none: an ordinary create of an empty file still skips", remote.writes)
|
||||
}
|
||||
})
|
||||
}
|
||||
+8
-11
@@ -28,11 +28,10 @@ var (
|
||||
)
|
||||
|
||||
type IamOptions struct {
|
||||
filer *string
|
||||
masters *string
|
||||
ip *string
|
||||
port *int
|
||||
selfServiceRequiresGrant *bool
|
||||
filer *string
|
||||
masters *string
|
||||
ip *string
|
||||
port *int
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -41,7 +40,6 @@ func init() {
|
||||
iamStandaloneOptions.masters = cmdIam.Flag.String("master", "localhost:9333", "comma-separated master servers")
|
||||
iamStandaloneOptions.ip = cmdIam.Flag.String("ip", util.DetectedHostAddress(), "iam server http listen ip address")
|
||||
iamStandaloneOptions.port = cmdIam.Flag.Int("port", 8111, "iam server http listen port")
|
||||
iamStandaloneOptions.selfServiceRequiresGrant = cmdIam.Flag.Bool("selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage)
|
||||
}
|
||||
|
||||
var cmdIam = &Command{
|
||||
@@ -103,11 +101,10 @@ func (iamopt *IamOptions) startIamServer() bool {
|
||||
masters := pb.ServerAddresses(*iamopt.masters).ToAddressMap()
|
||||
router := mux.NewRouter().SkipClean(true)
|
||||
iamApiServer, iamApiServer_err := iamapi.NewIamApiServer(router, &iamapi.IamServerOption{
|
||||
Masters: masters,
|
||||
Filers: filerAddresses,
|
||||
Port: *iamopt.port,
|
||||
GrpcDialOption: grpcDialOption,
|
||||
IamSelfServiceRequiresGrant: *iamopt.selfServiceRequiresGrant,
|
||||
Masters: masters,
|
||||
Filers: filerAddresses,
|
||||
Port: *iamopt.port,
|
||||
GrpcDialOption: grpcDialOption,
|
||||
})
|
||||
glog.V(0).Info("NewIamApiServer created")
|
||||
if iamApiServer_err != nil {
|
||||
|
||||
@@ -556,8 +556,6 @@ func initMiniS3Flags() {
|
||||
miniS3Options.cacheSizeMB = cmdMini.Flag.Int64("s3.cacheCapacityMB", 0, "in-memory chunk cache capacity in MB for S3 GETs shared across requests (0 disables)")
|
||||
miniS3Options.readerCacheSizeMB = cmdMini.Flag.Int64("s3.readerCacheSizeMB", 0, "memory budget in MiB for downloaded and in-flight reader buffers across all S3 GETs (0 means unlimited)")
|
||||
miniS3Options.allowUntrustedRemoteEndpoints = cmdMini.Flag.Bool("s3.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage)
|
||||
miniS3Options.allowBackslashInKey = cmdMini.Flag.Bool("s3.allowBackslashInKey", false, allowBackslashInKeyUsage)
|
||||
miniS3Options.iamSelfServiceRequiresGrant = cmdMini.Flag.Bool("s3.iam.selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage)
|
||||
// In mini mode, S3 uses the shared debug server started at line 681, not its own separate debug server
|
||||
miniS3Options.debug = new(bool) // explicitly false
|
||||
miniS3Options.debugPort = cmdMini.Flag.Int("s3.debug.port", 6060, "http port for debugging (unused in mini mode)")
|
||||
|
||||
+1
-8
@@ -84,8 +84,6 @@ type S3Options struct {
|
||||
readerCacheSizeMB *int64
|
||||
|
||||
allowUntrustedRemoteEndpoints *bool
|
||||
allowBackslashInKey *bool
|
||||
iamSelfServiceRequiresGrant *bool
|
||||
// shutdownCtx, when non-nil, tells startS3Server to gracefully shut down
|
||||
// its HTTP/gRPC servers once the ctx is cancelled, in addition to on
|
||||
// interrupt. Used by weed mini to orchestrate an ordered shutdown.
|
||||
@@ -142,8 +140,6 @@ func init() {
|
||||
s3StandaloneOptions.cacheSizeMB = cmdS3.Flag.Int64("cacheCapacityMB", 0, "in-memory chunk cache capacity in MB for S3 GETs shared across requests (0 disables)")
|
||||
s3StandaloneOptions.readerCacheSizeMB = cmdS3.Flag.Int64("readerCacheSizeMB", 0, "memory budget in MiB for downloaded and in-flight reader buffers across all S3 GETs (0 means unlimited)")
|
||||
s3StandaloneOptions.allowUntrustedRemoteEndpoints = cmdS3.Flag.Bool("allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage)
|
||||
s3StandaloneOptions.allowBackslashInKey = cmdS3.Flag.Bool("allowBackslashInKey", false, allowBackslashInKeyUsage)
|
||||
s3StandaloneOptions.iamSelfServiceRequiresGrant = cmdS3.Flag.Bool("iam.selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage)
|
||||
}
|
||||
|
||||
var cmdS3 = &Command{
|
||||
@@ -341,8 +337,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
|
||||
router := mux.NewRouter().SkipClean(true)
|
||||
var localFilerSocket string
|
||||
// The filer only listens on its local socket outside Windows.
|
||||
if s3opt.localFilerSocket != nil && runtime.GOOS != "windows" {
|
||||
if s3opt.localFilerSocket != nil {
|
||||
localFilerSocket = *s3opt.localFilerSocket
|
||||
}
|
||||
var s3ApiServer *s3api.S3ApiServer
|
||||
@@ -404,8 +399,6 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
MaxMB: filerMaxMB,
|
||||
|
||||
AllowUntrustedRemoteEndpoints: *s3opt.allowUntrustedRemoteEndpoints,
|
||||
AllowBackslashInKey: *s3opt.allowBackslashInKey,
|
||||
IamSelfServiceRequiresGrant: *s3opt.iamSelfServiceRequiresGrant,
|
||||
})
|
||||
if s3ApiServer_err != nil {
|
||||
glog.Fatalf("S3 API Server startup error: %v", s3ApiServer_err)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -33,22 +33,12 @@ recursive_delete = false
|
||||
# faster than previous leveldb, recommended.
|
||||
enabled = true
|
||||
dir = "./filerldb2" # directory to store level db files
|
||||
# optional tuning, applied to each of the 8 partitioned stores
|
||||
# block_cache_size_mb = 32 # sorted-table read cache
|
||||
# write_buffer_size_mb = 16 # memtable size before flushing to disk
|
||||
# block_size_kb = 4 # uncompressed block ('page') size inside table files
|
||||
# compaction_table_size_mb = 2 # target size of generated table files
|
||||
|
||||
[leveldb3]
|
||||
# similar to leveldb2.
|
||||
# each bucket has its own meta store.
|
||||
enabled = false
|
||||
dir = "./filerldb3" # directory to store level db files
|
||||
# optional tuning, applied to the default store and each bucket store
|
||||
# block_cache_size_mb = 32 # sorted-table read cache
|
||||
# write_buffer_size_mb = 16 # memtable size before flushing to disk
|
||||
# block_size_kb = 4 # uncompressed block ('page') size inside table files
|
||||
# compaction_table_size_mb = 2 # target size of generated table files
|
||||
|
||||
[rocksdb]
|
||||
# local on disk, similar to leveldb
|
||||
|
||||
@@ -28,10 +28,6 @@ region = "us-east-2"
|
||||
bucket = "your_bucket_name" # an existing bucket
|
||||
endpoint = ""
|
||||
storage_class = "STANDARD_IA"
|
||||
# optional HTTP client tuning for S3-compatible services:
|
||||
# disable_http2 = false # true keeps the client on HTTP/1.1, one connection per concurrent request
|
||||
# max_connections = 0 # cap on connections to the endpoint, 0 = no cap
|
||||
# idle_connection_timeout_seconds = 0 # close idle connections sooner, 0 = Go default (90s)
|
||||
|
||||
# create this number of logical volumes if no more writable volumes
|
||||
# count_x means how many copies of data.
|
||||
|
||||
@@ -195,12 +195,10 @@ func init() {
|
||||
s3Options.iamReadOnly = cmdServer.Flag.Bool("s3.iam.readOnly", true, "disable IAM write operations on this server")
|
||||
s3Options.cipher = cmdServer.Flag.Bool("s3.encryptVolumeData", false, "encrypt data on volume servers for S3 uploads")
|
||||
s3Options.externalUrl = cmdServer.Flag.String("s3.externalUrl", "", "the external URL clients use to connect (e.g. https://api.example.com:9000). Advertised to Iceberg and Lance clients, and tried first when verifying S3 signatures behind a reverse proxy. Falls back to S3_EXTERNAL_URL env var.")
|
||||
s3Options.allowBackslashInKey = cmdServer.Flag.Bool("s3.allowBackslashInKey", false, allowBackslashInKeyUsage)
|
||||
s3Options.defaultFileMode = cmdServer.Flag.String("s3.defaultFileMode", "", "default file mode for S3 uploaded objects, e.g. 0660, 0644, 0666")
|
||||
s3Options.cacheSizeMB = cmdServer.Flag.Int64("s3.cacheCapacityMB", 0, "in-memory chunk cache capacity in MB for S3 GETs shared across requests (0 disables)")
|
||||
s3Options.readerCacheSizeMB = cmdServer.Flag.Int64("s3.readerCacheSizeMB", 0, "memory budget in MiB for downloaded and in-flight reader buffers across all S3 GETs (0 means unlimited)")
|
||||
s3Options.allowUntrustedRemoteEndpoints = cmdServer.Flag.Bool("s3.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage)
|
||||
s3Options.iamSelfServiceRequiresGrant = cmdServer.Flag.Bool("s3.iam.selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage)
|
||||
|
||||
sftpOptions.port = cmdServer.Flag.Int("sftp.port", 2022, "SFTP server listen port")
|
||||
sftpOptions.sshPrivateKey = cmdServer.Flag.String("sftp.sshPrivateKey", "", "path to the SSH private key file for host authentication")
|
||||
@@ -216,7 +214,6 @@ func init() {
|
||||
sftpOptions.dataCenter = cmdServer.Flag.String("sftp.dataCenter", "", "prefer to read and write to volumes in this data center")
|
||||
sftpOptions.localSocket = cmdServer.Flag.String("sftp.localSocket", "", "default to /tmp/seaweedfs-sftp-<port>.sock")
|
||||
iamOptions.port = cmdServer.Flag.Int("iam.port", 8111, "iam server http listen port")
|
||||
iamOptions.selfServiceRequiresGrant = s3Options.iamSelfServiceRequiresGrant
|
||||
|
||||
webdavOptions.port = cmdServer.Flag.Int("webdav.port", 7333, "webdav server http listen port")
|
||||
webdavOptions.collection = cmdServer.Flag.String("webdav.collection", "", "collection to create the files")
|
||||
|
||||
@@ -3,7 +3,6 @@ package command
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
|
||||
@@ -13,11 +12,10 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
shellOptions shell.ShellOptions
|
||||
shellInitialFiler *string
|
||||
shellCluster *string
|
||||
shellDebug *bool
|
||||
shellConnectTimeout *time.Duration
|
||||
shellOptions shell.ShellOptions
|
||||
shellInitialFiler *string
|
||||
shellCluster *string
|
||||
shellDebug *bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -27,7 +25,6 @@ func init() {
|
||||
shellInitialFiler = cmdShell.Flag.String("filer", "", "filer host and port for initial connection, e.g. localhost:8888")
|
||||
shellCluster = cmdShell.Flag.String("cluster", "", "cluster defined in shell.toml")
|
||||
shellDebug = cmdShell.Flag.Bool("debug", false, "print informational logs to stderr")
|
||||
shellConnectTimeout = cmdShell.Flag.Duration("connectTimeout", 30*time.Second, "timeout for the initial master connection and filer discovery")
|
||||
}
|
||||
|
||||
var cmdShell = &Command{
|
||||
@@ -67,7 +64,6 @@ func runShell(command *Command, args []string) bool {
|
||||
}
|
||||
shellOptions.FilerAddress = pb.ServerAddress(filerAddress)
|
||||
shellOptions.Debug = *shellDebug
|
||||
shellOptions.ConnectTimeout = *shellConnectTimeout
|
||||
if shellOptions.Debug {
|
||||
fmt.Fprintf(os.Stderr, "master: %s filer: %s\n", *shellOptions.Masters, shellOptions.FilerAddress)
|
||||
}
|
||||
|
||||
+19
-73
@@ -6,7 +6,6 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
@@ -32,7 +31,6 @@ type UploadOptions struct {
|
||||
diskType *string
|
||||
maxMB *int
|
||||
usePublicUrl *bool
|
||||
concurrency *int
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -48,7 +46,6 @@ func init() {
|
||||
upload.ttl = cmdUpload.Flag.String("ttl", "", "time to live, e.g.: 1m, 1h, 1d, 1M, 1y")
|
||||
upload.maxMB = cmdUpload.Flag.Int("maxMB", 4, "split files larger than the limit")
|
||||
upload.usePublicUrl = cmdUpload.Flag.Bool("usePublicUrl", false, "upload to public url from volume server")
|
||||
upload.concurrency = cmdUpload.Flag.Int("c", 8, "concurrent file upload goroutines when uploading a folder")
|
||||
}
|
||||
|
||||
var cmdUpload = &Command{
|
||||
@@ -88,7 +85,6 @@ func runUpload(cmd *Command, args []string) bool {
|
||||
if *upload.dir == "" {
|
||||
return false
|
||||
}
|
||||
var filePaths []string
|
||||
err = filepath.Walk(util.ResolvePath(*upload.dir), func(path string, info os.FileInfo, err error) error {
|
||||
if err == nil {
|
||||
if !info.IsDir() {
|
||||
@@ -97,7 +93,23 @@ func runUpload(cmd *Command, args []string) bool {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
filePaths = append(filePaths, path)
|
||||
parts, e := operation.NewFileParts([]string{path})
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
results, e := operation.SubmitFiles(func(_ context.Context) pb.ServerAddress { return pb.ServerAddress(*upload.master) }, grpcDialOption, parts, operation.StoragePreference{
|
||||
Replication: *upload.replication,
|
||||
Collection: *upload.collection,
|
||||
DataCenter: *upload.dataCenter,
|
||||
Ttl: *upload.ttl,
|
||||
DiskType: *upload.diskType,
|
||||
MaxMB: *upload.maxMB,
|
||||
}, *upload.usePublicUrl)
|
||||
bytes, _ := json.Marshal(results)
|
||||
fmt.Println(string(bytes))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fmt.Println(err)
|
||||
@@ -106,72 +118,6 @@ func runUpload(cmd *Command, args []string) bool {
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
}
|
||||
|
||||
concurrency := *upload.concurrency
|
||||
if concurrency < 1 {
|
||||
concurrency = 1
|
||||
}
|
||||
masterFn := func(_ context.Context) pb.ServerAddress { return pb.ServerAddress(*upload.master) }
|
||||
pref := operation.StoragePreference{
|
||||
Replication: *upload.replication,
|
||||
Collection: *upload.collection,
|
||||
DataCenter: *upload.dataCenter,
|
||||
Ttl: *upload.ttl,
|
||||
DiskType: *upload.diskType,
|
||||
MaxMB: *upload.maxMB,
|
||||
}
|
||||
results := make([][]operation.SubmitResult, len(filePaths))
|
||||
ready := make([]chan struct{}, len(filePaths))
|
||||
for index := range ready {
|
||||
ready[index] = make(chan struct{})
|
||||
}
|
||||
printDone := make(chan bool, 1)
|
||||
go func() {
|
||||
failed := false
|
||||
for index := range ready {
|
||||
<-ready[index]
|
||||
bytes, _ := json.Marshal(results[index])
|
||||
fmt.Println(string(bytes))
|
||||
for _, r := range results[index] {
|
||||
if r.Error != "" {
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
printDone <- failed
|
||||
}()
|
||||
|
||||
sem := make(chan struct{}, concurrency)
|
||||
var wg sync.WaitGroup
|
||||
for index, filePath := range filePaths {
|
||||
sem <- struct{}{}
|
||||
wg.Add(1)
|
||||
go func(index int, filePath string) {
|
||||
defer close(ready[index])
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
parts, e := operation.NewFileParts([]string{filePath})
|
||||
if e != nil {
|
||||
results[index] = []operation.SubmitResult{{FileName: filepath.Base(filePath), Error: e.Error()}}
|
||||
return
|
||||
}
|
||||
fileResults, e := operation.SubmitFiles(masterFn, grpcDialOption, parts, pref, *upload.usePublicUrl)
|
||||
if e != nil {
|
||||
for i := range fileResults {
|
||||
if fileResults[i].Error == "" {
|
||||
fileResults[i].Error = e.Error()
|
||||
}
|
||||
}
|
||||
}
|
||||
results[index] = fileResults
|
||||
}(index, filePath)
|
||||
}
|
||||
wg.Wait()
|
||||
if <-printDone {
|
||||
return false
|
||||
}
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
@@ -188,12 +134,12 @@ func runUpload(cmd *Command, args []string) bool {
|
||||
DiskType: *upload.diskType,
|
||||
MaxMB: *upload.maxMB,
|
||||
}, *upload.usePublicUrl)
|
||||
bytes, _ := json.Marshal(results)
|
||||
fmt.Println(string(bytes))
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
return false
|
||||
}
|
||||
bytes, _ := json.Marshal(results)
|
||||
fmt.Println(string(bytes))
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -23,20 +23,14 @@ type SqlGenerator interface {
|
||||
GetSqlDeleteFolderChildren(tableName string) string
|
||||
GetSqlListExclusive(tableName string) string
|
||||
GetSqlListInclusive(tableName string) string
|
||||
// GetSqlScanPage returns the query and arguments selecting dirhash, name,
|
||||
// directory and meta of up to limit rows after the (dirhash, name) cursor.
|
||||
GetSqlScanPage(tableName string, dirhash int64, name string, limit int) (string, []interface{})
|
||||
GetSqlCreateTable(tableName string) string
|
||||
GetSqlDropTable(tableName string) string
|
||||
}
|
||||
|
||||
type AbstractSqlStore struct {
|
||||
SqlGenerator
|
||||
DB *sql.DB
|
||||
KvDB *sql.DB
|
||||
// ScanDB, when set, is the pool snapshot scans run on (SQLite's main pool
|
||||
// is a single connection that a long scan must not hold).
|
||||
ScanDB *sql.DB
|
||||
DB *sql.DB
|
||||
KvDB *sql.DB
|
||||
SupportBucketTable bool
|
||||
SkipDDL bool
|
||||
dbs map[string]bool
|
||||
@@ -463,9 +457,6 @@ func (store *AbstractSqlStore) Shutdown() {
|
||||
if store.KvDB != nil {
|
||||
store.KvDB.Close()
|
||||
}
|
||||
if store.ScanDB != nil {
|
||||
store.ScanDB.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func isValidBucket(bucket string) bool {
|
||||
|
||||
@@ -1,368 +0,0 @@
|
||||
package abstract_sql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
var _ filer.EntryScanner = (*AbstractSqlStore)(nil)
|
||||
|
||||
// scanTable is one table to read during a scan together with the path its
|
||||
// directory column is relative to: "" for the default table, whose rows hold
|
||||
// full directories, and "/buckets/<bucket>" for a per-bucket table.
|
||||
type scanTable struct {
|
||||
table string
|
||||
base string
|
||||
// cachedOnly marks a table that only a stale bucket cache remembers: its
|
||||
// bucket directory was already gone from the snapshot, so a missing table
|
||||
// means it was dropped meanwhile, not that rows are absent.
|
||||
cachedOnly bool
|
||||
}
|
||||
|
||||
// scanPageSize is how many rows one keyset page of a scan fetches.
|
||||
var scanPageSize = 1000
|
||||
|
||||
// SetScanPageSizeForTest lets tests drive the keyset cursor across pages. It
|
||||
// returns the previous size.
|
||||
func SetScanPageSizeForTest(n int) int {
|
||||
prev := scanPageSize
|
||||
scanPageSize = n
|
||||
return prev
|
||||
}
|
||||
|
||||
// ScanEntries implements filer.EntryScanner: every table that can hold an
|
||||
// entry below dirPath is read inside one REPEATABLE READ, read-only
|
||||
// transaction, in primary-key pages. All rows are seen as of one instant; a
|
||||
// rename committed meanwhile shows up under exactly one of its names. The
|
||||
// transaction takes no row locks and does not block writers; it does hold the
|
||||
// tables it has read against DDL, so a bucket deleted while the scan runs
|
||||
// drops its table once the scan ends. A page's cursor is closed before its
|
||||
// entries go to fn, so fn may read the store through the context it receives
|
||||
// (which carries the transaction) on the same connection.
|
||||
func (store *AbstractSqlStore) ScanEntries(ctx context.Context, dirPath util.FullPath, fn func(ctx context.Context, entry *filer.Entry) error) error {
|
||||
// Read before the transaction holds a connection: OnBucketCreation keeps
|
||||
// dbsLock while it waits for a connection of its own, so taking the lock
|
||||
// while holding a connection could deadlock on an exhausted pool.
|
||||
cachedBuckets := store.cachedBucketNames()
|
||||
|
||||
tx, err := store.beginSnapshotTx(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Read-only: nothing to commit, and a rollback releases the snapshot.
|
||||
defer tx.Rollback()
|
||||
|
||||
tables, err := store.scanTables(ctx, tx, dirPath, cachedBuckets)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Reads made through this context (getTxOrDB, kvDB) use the transaction
|
||||
// and therefore the snapshot.
|
||||
txCtx := context.WithValue(ctx, "tx", tx)
|
||||
// The root's own row may live in a table the scan does not read (a
|
||||
// bucket directory is in the default table, its contents in the bucket's).
|
||||
if root, err := store.readRowInSnapshot(txCtx, tx, dirPath); err != nil {
|
||||
return err
|
||||
} else if root != nil {
|
||||
if err := fn(txCtx, root); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, t := range tables {
|
||||
if err := store.scanOneTable(txCtx, tx, t, dirPath, fn); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readRowInSnapshot reads one entry's row inside the transaction, routing to
|
||||
// the table getTxOrDB would use but without its bucket-table creation. A
|
||||
// missing row is nil.
|
||||
func (store *AbstractSqlStore) readRowInSnapshot(ctx context.Context, tx *sql.Tx, p util.FullPath) (*filer.Entry, error) {
|
||||
if p == "/" {
|
||||
return nil, nil
|
||||
}
|
||||
parent, name := p.DirAndName()
|
||||
table, shortDir := DEFAULT_TABLE, parent
|
||||
if store.SupportBucketTable {
|
||||
if bucket := bucketTableFor(util.FullPath(parent)); bucket != "" {
|
||||
table = bucket
|
||||
if shortDir = strings.TrimPrefix(parent, bucketBase(bucket)); shortDir == "" {
|
||||
shortDir = "/"
|
||||
}
|
||||
}
|
||||
}
|
||||
var data []byte
|
||||
err := tx.QueryRowContext(ctx, store.GetSqlFind(table), util.HashStringToLong(shortDir), name, shortDir).Scan(&data)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, missingTableOr(err, table, fmt.Sprintf("read %s", p))
|
||||
}
|
||||
entry := &filer.Entry{FullPath: p}
|
||||
if err := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
|
||||
return nil, fmt.Errorf("decode %s: %v", p, err)
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// beginSnapshotTx starts the read-only REPEATABLE READ transaction that gives
|
||||
// one snapshot across statements. Nothing weaker is tried: under READ
|
||||
// COMMITTED each page would see a different snapshot, and the stream would
|
||||
// still be advertised as one.
|
||||
func (store *AbstractSqlStore) beginSnapshotTx(ctx context.Context) (*sql.Tx, error) {
|
||||
db := store.DB
|
||||
if store.ScanDB != nil {
|
||||
db = store.ScanDB
|
||||
} else if db.Stats().MaxOpenConnections == 1 {
|
||||
// The scan would hold the filer's only connection for its whole run.
|
||||
return nil, fmt.Errorf("%w: the store's single connection cannot be held for a scan", filer.ErrUnsupportedEntryScan)
|
||||
}
|
||||
// A BeginTx failure (a down database) must fail the traversal, not route it
|
||||
// to the walk: a recovered database lets the walk read renamed-away entries
|
||||
// as absent, the very loss this scan exists to prevent.
|
||||
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin snapshot: %v", err)
|
||||
}
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
func (store *AbstractSqlStore) cachedBucketNames() []string {
|
||||
store.dbsLock.Lock()
|
||||
defer store.dbsLock.Unlock()
|
||||
names := make([]string, 0, len(store.dbs))
|
||||
for name := range store.dbs {
|
||||
names = append(names, name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// scanTables picks the tables to read for dirPath: the default table alone,
|
||||
// one bucket's table for a path inside that bucket, or the default table plus
|
||||
// every bucket table (enumerated from /buckets inside the snapshot).
|
||||
func (store *AbstractSqlStore) scanTables(ctx context.Context, tx *sql.Tx, dirPath util.FullPath, cachedBuckets []string) ([]scanTable, error) {
|
||||
if !store.SupportBucketTable {
|
||||
return []scanTable{{table: DEFAULT_TABLE}}, nil
|
||||
}
|
||||
if bucket := bucketTableFor(dirPath); bucket != "" {
|
||||
return []scanTable{{table: bucket, base: bucketBase(bucket)}}, nil
|
||||
}
|
||||
tables := []scanTable{{table: DEFAULT_TABLE}}
|
||||
if dirPath != "/" && string(dirPath) != bucketsRoot {
|
||||
// Outside every bucket (e.g. /topics, or an internal /buckets/.system
|
||||
// folder): everything below dirPath is in the default table.
|
||||
return tables, nil
|
||||
}
|
||||
buckets, err := store.listBucketNames(ctx, tx, cachedBuckets)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, bucket := range buckets.names {
|
||||
tables = append(tables, scanTable{table: bucket, base: bucketBase(bucket), cachedOnly: !buckets.seen[bucket]})
|
||||
}
|
||||
return tables, nil
|
||||
}
|
||||
|
||||
const bucketsRoot = "/buckets"
|
||||
|
||||
func bucketBase(bucket string) string {
|
||||
return bucketsRoot + "/" + bucket
|
||||
}
|
||||
|
||||
// bucketTableFor returns the bucket whose table alone holds everything below
|
||||
// dirPath, or "" when dirPath is not inside a real bucket (as getTxOrDB routes).
|
||||
func bucketTableFor(dirPath util.FullPath) string {
|
||||
p := string(dirPath)
|
||||
if !strings.HasPrefix(p, bucketsRoot+"/") {
|
||||
return ""
|
||||
}
|
||||
rest := p[len(bucketsRoot)+1:]
|
||||
bucket := rest
|
||||
if i := strings.Index(rest, "/"); i >= 0 {
|
||||
bucket = rest[:i]
|
||||
}
|
||||
if bucket == "" || strings.HasPrefix(bucket, ".") || !isValidBucket(bucket) {
|
||||
return ""
|
||||
}
|
||||
return bucket
|
||||
}
|
||||
|
||||
// bucketNames is the snapshot-listed and cached-only buckets whose tables a
|
||||
// scan may read.
|
||||
type bucketNames struct {
|
||||
names []string
|
||||
seen map[string]bool // listed under /buckets inside the snapshot
|
||||
}
|
||||
|
||||
// listBucketNames reads the directories under /buckets within the snapshot
|
||||
// and keeps those that route to their own table, plus the buckets this
|
||||
// process has already seen (their directory entry may be gone, their rows not).
|
||||
func (store *AbstractSqlStore) listBucketNames(ctx context.Context, tx *sql.Tx, cachedBuckets []string) (bucketNames, error) {
|
||||
var names bucketNames
|
||||
names.seen = make(map[string]bool)
|
||||
added := make(map[string]bool)
|
||||
add := func(name string) {
|
||||
if added[name] || strings.HasPrefix(name, ".") || !isValidBucket(name) {
|
||||
return
|
||||
}
|
||||
added[name] = true
|
||||
names.names = append(names.names, name)
|
||||
}
|
||||
|
||||
const page = 1000
|
||||
startFrom := ""
|
||||
for {
|
||||
type row struct {
|
||||
name string
|
||||
data []byte
|
||||
}
|
||||
var rows []row
|
||||
if err := func() error {
|
||||
res, err := tx.QueryContext(ctx, store.GetSqlListExclusive(DEFAULT_TABLE), util.HashStringToLong(bucketsRoot), startFrom, bucketsRoot, "%", page)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list %s: %v", bucketsRoot, err)
|
||||
}
|
||||
defer res.Close()
|
||||
for res.Next() {
|
||||
var r row
|
||||
if err := res.Scan(&r.name, &r.data); err != nil {
|
||||
return fmt.Errorf("scan %s: %v", bucketsRoot, err)
|
||||
}
|
||||
rows = append(rows, r)
|
||||
}
|
||||
return res.Err()
|
||||
}(); err != nil {
|
||||
return bucketNames{}, err
|
||||
}
|
||||
for _, r := range rows {
|
||||
startFrom = r.name
|
||||
entry := &filer.Entry{FullPath: util.NewFullPath(bucketsRoot, r.name)}
|
||||
if err := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(r.data)); err != nil {
|
||||
return bucketNames{}, fmt.Errorf("scan decode %s: %v", entry.FullPath, err)
|
||||
}
|
||||
if entry.IsDirectory() {
|
||||
names.seen[r.name] = true
|
||||
add(r.name)
|
||||
}
|
||||
}
|
||||
if len(rows) < page {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for _, name := range cachedBuckets {
|
||||
add(name)
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// scanOneTable reads one table in primary-key pages and hands the entries
|
||||
// strictly below dirPath to fn (the root itself is read separately). Key-value
|
||||
// records share the default table; GenDirAndName stores the raw key bytes as
|
||||
// their dirhash while entry rows hash the directory, so the mismatch
|
||||
// identifies them exactly.
|
||||
func (store *AbstractSqlStore) scanOneTable(ctx context.Context, tx *sql.Tx, t scanTable, dirPath util.FullPath, fn func(ctx context.Context, entry *filer.Entry) error) error {
|
||||
type row struct {
|
||||
dirHash int64
|
||||
name, dir string
|
||||
data []byte
|
||||
}
|
||||
cursorHash, cursorName := int64(math.MinInt64), ""
|
||||
firstPage := true
|
||||
for {
|
||||
var page []row
|
||||
if t.cachedOnly && firstPage {
|
||||
// A missing table can only be met by the first page read: once a
|
||||
// row came back the tx holds the table against a drop. On
|
||||
// PostgreSQL the failed query aborts the transaction, so the skip
|
||||
// needs a savepoint to roll back to before the next table's read.
|
||||
if _, err := tx.ExecContext(ctx, "SAVEPOINT seaweed_scan_bucket"); err != nil {
|
||||
return fmt.Errorf("scan table %s: %v", t.table, err)
|
||||
}
|
||||
}
|
||||
sqlText, args := store.GetSqlScanPage(t.table, cursorHash, cursorName, scanPageSize)
|
||||
rows, err := tx.QueryContext(ctx, sqlText, args...)
|
||||
if err != nil {
|
||||
if t.cachedOnly && isMissingTableError(err) {
|
||||
tx.ExecContext(ctx, "ROLLBACK TO SAVEPOINT seaweed_scan_bucket")
|
||||
return nil // a cached-only name whose table was dropped meanwhile
|
||||
}
|
||||
return missingTableOr(err, t.table, fmt.Sprintf("scan table %s", t.table))
|
||||
}
|
||||
firstPage = false
|
||||
if err := func() error {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var r row
|
||||
if err := rows.Scan(&r.dirHash, &r.name, &r.dir, &r.data); err != nil {
|
||||
return fmt.Errorf("scan table %s: %v", t.table, err)
|
||||
}
|
||||
page = append(page, r)
|
||||
}
|
||||
return rows.Err()
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, r := range page {
|
||||
cursorHash, cursorName = r.dirHash, r.name
|
||||
if r.dirHash != util.HashStringToLong(r.dir) {
|
||||
continue // a key-value record, see GenDirAndName
|
||||
}
|
||||
fullPath := util.NewFullPath(t.base+r.dir, r.name)
|
||||
if !isStrictlyBelow(fullPath, dirPath) {
|
||||
continue
|
||||
}
|
||||
entry := &filer.Entry{FullPath: fullPath}
|
||||
if err := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(r.data)); err != nil {
|
||||
return fmt.Errorf("scan decode %s: %v", fullPath, err)
|
||||
}
|
||||
if err := fn(ctx, entry); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(page) < scanPageSize {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// missingTableOr names the condition when a bucket's table is not there. The
|
||||
// scan fails closed: from inside the snapshot a table that was never created
|
||||
// cannot be told from one dropped a moment ago, whose rows the snapshot still
|
||||
// counts, and treating either as empty would let fsck purge referenced chunks.
|
||||
func missingTableOr(err error, table, what string) error {
|
||||
if table != DEFAULT_TABLE && isMissingTableError(err) {
|
||||
return fmt.Errorf("bucket %s has a directory entry but no table (never created, or dropped during the scan): %v", table, err)
|
||||
}
|
||||
return fmt.Errorf("%s: %v", what, err)
|
||||
}
|
||||
|
||||
// isMissingTableError recognizes a missing table by message, as InsertEntry
|
||||
// recognizes duplicates: PostgreSQL `relation "x" does not exist` (SQLSTATE
|
||||
// 42P01), MySQL error 1146 (SQLSTATE 42S02), SQLite "no such table".
|
||||
func isMissingTableError(err error) bool {
|
||||
msg := strings.ToLower(err.Error())
|
||||
return strings.Contains(msg, "42p01") ||
|
||||
(strings.Contains(msg, "relation \"") && strings.Contains(msg, "does not exist")) ||
|
||||
strings.Contains(msg, "42s02") ||
|
||||
strings.Contains(msg, "error 1146") ||
|
||||
strings.Contains(msg, "no such table")
|
||||
}
|
||||
|
||||
// isStrictlyBelow reports whether p is a descendant of dir (not dir itself).
|
||||
func isStrictlyBelow(p, dir util.FullPath) bool {
|
||||
if dir == "/" {
|
||||
return p != "/"
|
||||
}
|
||||
return strings.HasPrefix(string(p), string(dir)+"/")
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package abstract_sql
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func TestBucketTableFor(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"/": "",
|
||||
"/buckets": "",
|
||||
"/buckets/": "",
|
||||
"/buckets/mybucket": "mybucket",
|
||||
"/buckets/mybucket/a/b": "mybucket",
|
||||
"/buckets/.system/owners": "",
|
||||
"/buckets/Invalid_Bucket/x": "",
|
||||
"/topics/.system/log": "",
|
||||
"/bucketsfoo/mybucket": "",
|
||||
}
|
||||
for path, want := range cases {
|
||||
if got := bucketTableFor(util.FullPath(path)); got != want {
|
||||
t.Errorf("bucketTableFor(%s) = %q, want %q", path, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only a missing table may be skipped; any other schema error must fail the
|
||||
// scan, or a bucket's live chunks would be reported as orphans.
|
||||
func TestIsMissingTableError(t *testing.T) {
|
||||
for _, msg := range []string{
|
||||
`ERROR: relation "ghost" does not exist (SQLSTATE 42P01)`,
|
||||
`Error 1146 (42S02): Table 'seaweedfs.ghost' doesn't exist`,
|
||||
`SQL logic error: no such table: ghost (1)`,
|
||||
} {
|
||||
if !isMissingTableError(errors.New(msg)) {
|
||||
t.Errorf("not recognized as a missing table: %s", msg)
|
||||
}
|
||||
}
|
||||
for _, msg := range []string{
|
||||
`ERROR: column "directory" does not exist (SQLSTATE 42703)`,
|
||||
`Error 1054 (42S22): Unknown column 'directory' in 'field list'`,
|
||||
`SQL logic error: no such column: directory (1)`,
|
||||
"connection refused",
|
||||
} {
|
||||
if isMissingTableError(errors.New(msg)) {
|
||||
t.Errorf("wrongly taken for a missing table: %s", msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -413,28 +413,6 @@ func (f *Filer) RollbackTransaction(ctx context.Context) error {
|
||||
return f.Store.RollbackTransaction(ctx)
|
||||
}
|
||||
|
||||
type syncWriteKey struct{}
|
||||
|
||||
// WithSyncWrite marks the entry writes under ctx durable-on-ack: a store that
|
||||
// buffers writes by default must flush them before returning.
|
||||
func WithSyncWrite(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, syncWriteKey{}, true)
|
||||
}
|
||||
|
||||
// SyncWrite reports whether ctx carries a durability request for entry writes.
|
||||
func SyncWrite(ctx context.Context) bool {
|
||||
return ctx.Value(syncWriteKey{}) != nil
|
||||
}
|
||||
|
||||
// syncWriteContext flags ctx when the storage rule on p asks for fsync, so the
|
||||
// store write is held to the same durability as the data path.
|
||||
func (f *Filer) syncWriteContext(ctx context.Context, p util.FullPath) context.Context {
|
||||
if f.FilerConf != nil && f.FilerConf.MatchStorageRule(string(p)).Fsync {
|
||||
return WithSyncWrite(ctx)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
// CreateEntry creates or replaces an entry. When existing is non-nil the caller
|
||||
// has already fetched the current entry at this path under a path lock, and it
|
||||
// is reused instead of looking the store up again; pass nil to have CreateEntry
|
||||
@@ -445,8 +423,6 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry,
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx = f.syncWriteContext(ctx, entry.FullPath)
|
||||
|
||||
if entry.FullPath.IsLongerFileName(maxFilenameLength) {
|
||||
return filer_pb.ErrEntryNameTooLong
|
||||
}
|
||||
@@ -652,7 +628,6 @@ func (f *Filer) DirectoryAttributes(ctx context.Context, dirPath util.FullPath)
|
||||
// deleted with, so a restore cannot hand back a directory more permissive than the one
|
||||
// it replaces - including when someone else already put it back with wider ones.
|
||||
func (f *Filer) EnsureDirectoryEntry(ctx context.Context, dirPath util.FullPath, attrs empty_folder_cleanup.DirectoryAttributes) error {
|
||||
ctx = f.syncWriteContext(ctx, dirPath)
|
||||
existing, err := f.FindEntry(ctx, dirPath)
|
||||
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return err
|
||||
@@ -702,7 +677,6 @@ func (f *Filer) EnsureDirectoryEntry(ctx context.Context, dirPath util.FullPath,
|
||||
}
|
||||
|
||||
func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry, isFromOtherCluster bool) (err error) {
|
||||
ctx = f.syncWriteContext(ctx, entry.FullPath)
|
||||
if oldEntry != nil {
|
||||
entry.Attr.Crtime = oldEntry.Attr.Crtime
|
||||
if oldEntry.Attr.Inode != 0 {
|
||||
|
||||
@@ -122,8 +122,6 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx = f.syncWriteContext(ctx, p)
|
||||
|
||||
entry, findErr := f.FindEntry(ctx, p)
|
||||
if findErr != nil {
|
||||
return findErr
|
||||
|
||||
@@ -44,22 +44,6 @@ type FilerStore interface {
|
||||
Shutdown()
|
||||
}
|
||||
|
||||
// ErrUnsupportedEntryScan is returned by EntryScanner.ScanEntries, before
|
||||
// any entry is visited, when the store cannot serve the scan.
|
||||
var ErrUnsupportedEntryScan = errors.New("entry scan not supported by this filer store")
|
||||
|
||||
// EntryScanner is an optional FilerStore capability: visit every entry at and
|
||||
// below dirPath, in any order, from one consistent snapshot of the store.
|
||||
//
|
||||
// A directory walk sees each directory at a different time, so an entry
|
||||
// renamed from a directory not yet listed into one already listed is never
|
||||
// seen; volume.fsck then purges its chunks as orphans. A snapshot sees it
|
||||
// exactly once. The context handed to fn carries the snapshot, so store reads
|
||||
// made with it (hard-link records) see the same instant.
|
||||
type EntryScanner interface {
|
||||
ScanEntries(ctx context.Context, dirPath util.FullPath, fn func(ctx context.Context, entry *Entry) error) error
|
||||
}
|
||||
|
||||
type BucketAware interface {
|
||||
OnBucketCreation(bucket string)
|
||||
OnBucketDeletion(bucket string)
|
||||
|
||||
@@ -2,7 +2,6 @@ package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
@@ -20,7 +19,6 @@ import (
|
||||
var (
|
||||
_ = VirtualFilerStore(&FilerStoreWrapper{})
|
||||
_ = Debuggable(&FilerStoreWrapper{})
|
||||
_ = EntryScanner(&FilerStoreWrapper{})
|
||||
)
|
||||
|
||||
type VirtualFilerStore interface {
|
||||
@@ -366,33 +364,6 @@ func (fsw *FilerStoreWrapper) ListDirectoryPrefixedEntries(ctx context.Context,
|
||||
return lastFileName, err
|
||||
}
|
||||
|
||||
// ScanEntries delegates to the default store. With path-specific stores
|
||||
// configured, entries below dirPath could live in several stores and one
|
||||
// snapshot per store is not one snapshot, so the scan is declined. Hard links
|
||||
// are resolved inside the snapshot; a store error fails the scan (the per-path
|
||||
// copy can be stale), a missing record falls back to it as listings do.
|
||||
func (fsw *FilerStoreWrapper) ScanEntries(ctx context.Context, dirPath util.FullPath, fn func(ctx context.Context, entry *Entry) error) error {
|
||||
if fsw.hasPathSpecificStore {
|
||||
return ErrUnsupportedEntryScan
|
||||
}
|
||||
scanner, ok := fsw.defaultStore.(EntryScanner)
|
||||
if !ok {
|
||||
return ErrUnsupportedEntryScan
|
||||
}
|
||||
stats.FilerStoreCounter.WithLabelValues(fsw.defaultStore.GetName(), "scan").Inc()
|
||||
start := time.Now()
|
||||
defer func() {
|
||||
stats.FilerStoreHistogram.WithLabelValues(fsw.defaultStore.GetName(), "scan").Observe(time.Since(start).Seconds())
|
||||
}()
|
||||
return scanner.ScanEntries(ctx, dirPath, func(scanCtx context.Context, entry *Entry) error {
|
||||
if err := fsw.maybeReadHardLink(scanCtx, entry); err != nil && !errors.Is(err, ErrKvNotFound) {
|
||||
return fmt.Errorf("resolve hard link of %s: %w", entry.FullPath, err)
|
||||
}
|
||||
filer_pb.AfterEntryDeserialization(entry.GetChunks())
|
||||
return fn(scanCtx, entry)
|
||||
})
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) prefixFilterEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (lastFileName string, err error) {
|
||||
actualStore := fsw.getActualStore(dirPath + "/")
|
||||
|
||||
|
||||
@@ -79,15 +79,6 @@ func (store *LevelDBStore) RollbackTransaction(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
var syncWriteOptions = &opt.WriteOptions{Sync: true}
|
||||
|
||||
func writeOptions(ctx context.Context) *opt.WriteOptions {
|
||||
if filer.SyncWrite(ctx) {
|
||||
return syncWriteOptions
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *LevelDBStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
|
||||
key := genKey(entry.DirAndName())
|
||||
|
||||
@@ -100,7 +91,7 @@ func (store *LevelDBStore) InsertEntry(ctx context.Context, entry *filer.Entry)
|
||||
value = weed_util.MaybeGzipData(value)
|
||||
}
|
||||
|
||||
err = store.db.Put(key, value, writeOptions(ctx))
|
||||
err = store.db.Put(key, value, nil)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
|
||||
@@ -177,7 +168,7 @@ func (store *LevelDBStore) FindEntry(ctx context.Context, fullpath weed_util.Ful
|
||||
func (store *LevelDBStore) DeleteEntry(ctx context.Context, fullpath weed_util.FullPath) (err error) {
|
||||
key := genKey(fullpath.DirAndName())
|
||||
|
||||
err = store.db.Delete(key, writeOptions(ctx))
|
||||
err = store.db.Delete(key, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete %s : %v", fullpath, err)
|
||||
}
|
||||
@@ -204,7 +195,7 @@ func (store *LevelDBStore) DeleteFolderChildren(ctx context.Context, fullpath we
|
||||
}
|
||||
iter.Release()
|
||||
|
||||
err = store.db.Write(batch, writeOptions(ctx))
|
||||
err = store.db.Write(batch, nil)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete %s : %v", fullpath, err)
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
|
||||
"github.com/syndtr/goleveldb/leveldb"
|
||||
@@ -29,11 +28,6 @@ type LevelDB2Store struct {
|
||||
dbs []*leveldb.DB
|
||||
dbCount int
|
||||
ReadOnly bool
|
||||
|
||||
blockCacheSizeMB int
|
||||
writeBufferSizeMB int
|
||||
blockSizeKB int
|
||||
compactionTableSizeMB int
|
||||
}
|
||||
|
||||
func (store *LevelDB2Store) GetName() string {
|
||||
@@ -42,54 +36,9 @@ func (store *LevelDB2Store) GetName() string {
|
||||
|
||||
func (store *LevelDB2Store) Initialize(configuration weed_util.Configuration, prefix string) (err error) {
|
||||
dir := configuration.GetString(prefix + "dir")
|
||||
store.blockCacheSizeMB = configuration.GetInt(prefix + "block_cache_size_mb")
|
||||
store.writeBufferSizeMB = configuration.GetInt(prefix + "write_buffer_size_mb")
|
||||
store.blockSizeKB = configuration.GetInt(prefix + "block_size_kb")
|
||||
store.compactionTableSizeMB = configuration.GetInt(prefix + "compaction_table_size_mb")
|
||||
if err := store.validateSizeOptions(); err != nil {
|
||||
return err
|
||||
}
|
||||
return store.initialize(dir, 8)
|
||||
}
|
||||
|
||||
// validateSizeOptions rejects sizes too large to convert to bytes without
|
||||
// overflowing int on this platform.
|
||||
func (store *LevelDB2Store) validateSizeOptions() error {
|
||||
for name, kv := range map[string][2]int{
|
||||
"block_cache_size_mb": {store.blockCacheSizeMB, 1 << 20},
|
||||
"write_buffer_size_mb": {store.writeBufferSizeMB, 1 << 20},
|
||||
"block_size_kb": {store.blockSizeKB, 1 << 10},
|
||||
"compaction_table_size_mb": {store.compactionTableSizeMB, 1 << 20},
|
||||
} {
|
||||
if kv[0] > math.MaxInt/kv[1] {
|
||||
return fmt.Errorf("leveldb2 option %s=%d overflows int", name, kv[0])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *LevelDB2Store) buildOptions() *opt.Options {
|
||||
opts := &opt.Options{
|
||||
BlockCacheCapacity: 32 * 1024 * 1024, // default value is 8MiB
|
||||
WriteBuffer: 16 * 1024 * 1024, // default value is 4MiB
|
||||
Filter: filter.NewBloomFilter(8), // false positive rate 0.02
|
||||
ReadOnly: store.ReadOnly,
|
||||
}
|
||||
if store.blockCacheSizeMB > 0 {
|
||||
opts.BlockCacheCapacity = store.blockCacheSizeMB * 1024 * 1024
|
||||
}
|
||||
if store.writeBufferSizeMB > 0 {
|
||||
opts.WriteBuffer = store.writeBufferSizeMB * 1024 * 1024
|
||||
}
|
||||
if store.blockSizeKB > 0 {
|
||||
opts.BlockSize = store.blockSizeKB * 1024
|
||||
}
|
||||
if store.compactionTableSizeMB > 0 {
|
||||
opts.CompactionTableSize = store.compactionTableSizeMB * 1024 * 1024
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
func (store *LevelDB2Store) initialize(dir string, dbCount int) (err error) {
|
||||
glog.Infof("filer store leveldb2 dir: %s", dir)
|
||||
os.MkdirAll(dir, 0755)
|
||||
@@ -97,7 +46,12 @@ func (store *LevelDB2Store) initialize(dir string, dbCount int) (err error) {
|
||||
return fmt.Errorf("Check Level Folder %s Writable: %s", dir, err)
|
||||
}
|
||||
|
||||
opts := store.buildOptions()
|
||||
opts := &opt.Options{
|
||||
BlockCacheCapacity: 32 * 1024 * 1024, // default value is 8MiB
|
||||
WriteBuffer: 16 * 1024 * 1024, // default value is 4MiB
|
||||
Filter: filter.NewBloomFilter(8), // false positive rate 0.02
|
||||
ReadOnly: store.ReadOnly,
|
||||
}
|
||||
|
||||
for d := 0; d < dbCount; d++ {
|
||||
dbFolder := fmt.Sprintf("%s/%02d", dir, d)
|
||||
@@ -127,15 +81,6 @@ func (store *LevelDB2Store) RollbackTransaction(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
var syncWriteOptions = &opt.WriteOptions{Sync: true}
|
||||
|
||||
func writeOptions(ctx context.Context) *opt.WriteOptions {
|
||||
if filer.SyncWrite(ctx) {
|
||||
return syncWriteOptions
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *LevelDB2Store) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
|
||||
dir, name := entry.DirAndName()
|
||||
key, partitionId := genKey(dir, name, store.dbCount)
|
||||
@@ -149,7 +94,7 @@ func (store *LevelDB2Store) InsertEntry(ctx context.Context, entry *filer.Entry)
|
||||
value = weed_util.MaybeGzipData(value)
|
||||
}
|
||||
|
||||
err = store.dbs[partitionId].Put(key, value, writeOptions(ctx))
|
||||
err = store.dbs[partitionId].Put(key, value, nil)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
|
||||
@@ -195,7 +140,7 @@ func (store *LevelDB2Store) DeleteEntry(ctx context.Context, fullpath weed_util.
|
||||
dir, name := fullpath.DirAndName()
|
||||
key, partitionId := genKey(dir, name, store.dbCount)
|
||||
|
||||
err = store.dbs[partitionId].Delete(key, writeOptions(ctx))
|
||||
err = store.dbs[partitionId].Delete(key, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete %s : %v", fullpath, err)
|
||||
}
|
||||
@@ -222,7 +167,7 @@ func (store *LevelDB2Store) DeleteFolderChildren(ctx context.Context, fullpath w
|
||||
}
|
||||
iter.Release()
|
||||
|
||||
err = store.dbs[partitionId].Write(batch, writeOptions(ctx))
|
||||
err = store.dbs[partitionId].Write(batch, nil)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete %s : %v", fullpath, err)
|
||||
|
||||
@@ -2,8 +2,6 @@ package leveldb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
@@ -64,93 +62,6 @@ func TestCreateAndFind(t *testing.T) {
|
||||
|
||||
}
|
||||
|
||||
type fakeConfiguration map[string]interface{}
|
||||
|
||||
func (c fakeConfiguration) GetString(key string) string {
|
||||
value, _ := c[key].(string)
|
||||
return value
|
||||
}
|
||||
|
||||
func (c fakeConfiguration) GetBool(key string) bool {
|
||||
value, _ := c[key].(bool)
|
||||
return value
|
||||
}
|
||||
|
||||
func (c fakeConfiguration) GetInt(key string) int {
|
||||
value, _ := c[key].(int)
|
||||
return value
|
||||
}
|
||||
|
||||
func (c fakeConfiguration) GetStringSlice(key string) []string {
|
||||
value, _ := c[key].([]string)
|
||||
return value
|
||||
}
|
||||
|
||||
func (c fakeConfiguration) SetDefault(key string, value interface{}) {
|
||||
if _, found := c[key]; !found {
|
||||
c[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeOptions(t *testing.T) {
|
||||
store := &LevelDB2Store{}
|
||||
if err := store.Initialize(fakeConfiguration{
|
||||
"leveldb2.dir": t.TempDir(),
|
||||
"leveldb2.block_cache_size_mb": 64,
|
||||
"leveldb2.write_buffer_size_mb": 32,
|
||||
"leveldb2.block_size_kb": 16,
|
||||
"leveldb2.compaction_table_size_mb": 8,
|
||||
}, "leveldb2."); err != nil {
|
||||
t.Fatalf("initialize: %v", err)
|
||||
}
|
||||
defer store.Shutdown()
|
||||
|
||||
opts := store.buildOptions()
|
||||
if opts.BlockCacheCapacity != 64*1024*1024 {
|
||||
t.Errorf("block cache %d, want 64MiB", opts.BlockCacheCapacity)
|
||||
}
|
||||
if opts.WriteBuffer != 32*1024*1024 {
|
||||
t.Errorf("write buffer %d, want 32MiB", opts.WriteBuffer)
|
||||
}
|
||||
if opts.BlockSize != 16*1024 {
|
||||
t.Errorf("block size %d, want 16KiB", opts.BlockSize)
|
||||
}
|
||||
if opts.CompactionTableSize != 8*1024*1024 {
|
||||
t.Errorf("compaction table size %d, want 8MiB", opts.CompactionTableSize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeDefaultOptions(t *testing.T) {
|
||||
store := &LevelDB2Store{}
|
||||
if err := store.Initialize(fakeConfiguration{
|
||||
"leveldb2.dir": t.TempDir(),
|
||||
"leveldb2.block_cache_size_mb": -1,
|
||||
"leveldb2.write_buffer_size_mb": 0,
|
||||
}, "leveldb2."); err != nil {
|
||||
t.Fatalf("initialize: %v", err)
|
||||
}
|
||||
defer store.Shutdown()
|
||||
|
||||
opts := store.buildOptions()
|
||||
if opts.BlockCacheCapacity != 32*1024*1024 {
|
||||
t.Errorf("block cache %d, want the 32MiB default", opts.BlockCacheCapacity)
|
||||
}
|
||||
if opts.WriteBuffer != 16*1024*1024 {
|
||||
t.Errorf("write buffer %d, want the 16MiB default", opts.WriteBuffer)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeRejectsOversizedOption(t *testing.T) {
|
||||
store := &LevelDB2Store{}
|
||||
err := store.Initialize(fakeConfiguration{
|
||||
"leveldb2.dir": t.TempDir(),
|
||||
"leveldb2.write_buffer_size_mb": math.MaxInt/(1<<20) + 1,
|
||||
}, "leveldb2.")
|
||||
if err == nil || !strings.Contains(err.Error(), "write_buffer_size_mb") {
|
||||
t.Fatalf("expected overflow rejection, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyRoot(t *testing.T) {
|
||||
testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
|
||||
dir := t.TempDir()
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -36,11 +35,6 @@ type LevelDB3Store struct {
|
||||
dbs map[string]*leveldb.DB
|
||||
dbsLock sync.RWMutex
|
||||
ReadOnly bool
|
||||
|
||||
blockCacheSizeMB int
|
||||
writeBufferSizeMB int
|
||||
blockSizeKB int
|
||||
compactionTableSizeMB int
|
||||
}
|
||||
|
||||
func (store *LevelDB3Store) GetName() string {
|
||||
@@ -49,58 +43,9 @@ func (store *LevelDB3Store) GetName() string {
|
||||
|
||||
func (store *LevelDB3Store) Initialize(configuration weed_util.Configuration, prefix string) (err error) {
|
||||
dir := configuration.GetString(prefix + "dir")
|
||||
store.blockCacheSizeMB = configuration.GetInt(prefix + "block_cache_size_mb")
|
||||
store.writeBufferSizeMB = configuration.GetInt(prefix + "write_buffer_size_mb")
|
||||
store.blockSizeKB = configuration.GetInt(prefix + "block_size_kb")
|
||||
store.compactionTableSizeMB = configuration.GetInt(prefix + "compaction_table_size_mb")
|
||||
if err := store.validateSizeOptions(); err != nil {
|
||||
return err
|
||||
}
|
||||
return store.initialize(dir)
|
||||
}
|
||||
|
||||
// validateSizeOptions rejects sizes too large to convert to bytes without
|
||||
// overflowing int on this platform.
|
||||
func (store *LevelDB3Store) validateSizeOptions() error {
|
||||
for name, kv := range map[string][2]int{
|
||||
"block_cache_size_mb": {store.blockCacheSizeMB, 1 << 20},
|
||||
"write_buffer_size_mb": {store.writeBufferSizeMB, 1 << 20},
|
||||
"block_size_kb": {store.blockSizeKB, 1 << 10},
|
||||
"compaction_table_size_mb": {store.compactionTableSizeMB, 1 << 20},
|
||||
} {
|
||||
if kv[0] > math.MaxInt/kv[1] {
|
||||
return fmt.Errorf("leveldb3 option %s=%d overflows int", name, kv[0])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *LevelDB3Store) buildOptions(name string) *opt.Options {
|
||||
opts := &opt.Options{
|
||||
BlockCacheCapacity: 32 * 1024 * 1024, // default value is 8MiB
|
||||
WriteBuffer: 16 * 1024 * 1024, // default value is 4MiB
|
||||
Filter: filter.NewBloomFilter(8),
|
||||
ReadOnly: store.ReadOnly,
|
||||
}
|
||||
if name != DEFAULT {
|
||||
opts.BlockCacheCapacity = 16 * 1024 * 1024 // default value is 8MiB
|
||||
opts.WriteBuffer = 8 * 1024 * 1024 // default value is 4MiB
|
||||
}
|
||||
if store.blockCacheSizeMB > 0 {
|
||||
opts.BlockCacheCapacity = store.blockCacheSizeMB * 1024 * 1024
|
||||
}
|
||||
if store.writeBufferSizeMB > 0 {
|
||||
opts.WriteBuffer = store.writeBufferSizeMB * 1024 * 1024
|
||||
}
|
||||
if store.blockSizeKB > 0 {
|
||||
opts.BlockSize = store.blockSizeKB * 1024
|
||||
}
|
||||
if store.compactionTableSizeMB > 0 {
|
||||
opts.CompactionTableSize = store.compactionTableSizeMB * 1024 * 1024
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
func (store *LevelDB3Store) initialize(dir string) (err error) {
|
||||
glog.Infof("filer store leveldb3 dir: %s", dir)
|
||||
os.MkdirAll(dir, 0755)
|
||||
@@ -120,7 +65,21 @@ func (store *LevelDB3Store) initialize(dir string) (err error) {
|
||||
}
|
||||
|
||||
func (store *LevelDB3Store) loadDB(name string) (*leveldb.DB, error) {
|
||||
opts := store.buildOptions(name)
|
||||
bloom := filter.NewBloomFilter(8) // false positive rate 0.02
|
||||
opts := &opt.Options{
|
||||
BlockCacheCapacity: 32 * 1024 * 1024, // default value is 8MiB
|
||||
WriteBuffer: 16 * 1024 * 1024, // default value is 4MiB
|
||||
Filter: bloom,
|
||||
ReadOnly: store.ReadOnly,
|
||||
}
|
||||
if name != DEFAULT {
|
||||
opts = &opt.Options{
|
||||
BlockCacheCapacity: 16 * 1024 * 1024, // default value is 8MiB
|
||||
WriteBuffer: 8 * 1024 * 1024, // default value is 4MiB
|
||||
Filter: bloom,
|
||||
ReadOnly: store.ReadOnly,
|
||||
}
|
||||
}
|
||||
|
||||
dbFolder := fmt.Sprintf("%s/%s", store.dir, name)
|
||||
os.MkdirAll(dbFolder, 0755)
|
||||
@@ -221,15 +180,6 @@ func (store *LevelDB3Store) RollbackTransaction(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
var syncWriteOptions = &opt.WriteOptions{Sync: true}
|
||||
|
||||
func writeOptions(ctx context.Context) *opt.WriteOptions {
|
||||
if filer.SyncWrite(ctx) {
|
||||
return syncWriteOptions
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *LevelDB3Store) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
|
||||
|
||||
db, _, shortPath, err := store.findDB(entry.FullPath, false)
|
||||
@@ -249,7 +199,7 @@ func (store *LevelDB3Store) InsertEntry(ctx context.Context, entry *filer.Entry)
|
||||
value = weed_util.MaybeGzipData(value)
|
||||
}
|
||||
|
||||
err = db.Put(key, value, writeOptions(ctx))
|
||||
err = db.Put(key, value, nil)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
|
||||
@@ -307,7 +257,7 @@ func (store *LevelDB3Store) DeleteEntry(ctx context.Context, fullpath weed_util.
|
||||
dir, name := shortPath.DirAndName()
|
||||
key := genKey(dir, name)
|
||||
|
||||
err = db.Delete(key, writeOptions(ctx))
|
||||
err = db.Delete(key, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete %s : %v", fullpath, err)
|
||||
}
|
||||
@@ -348,7 +298,7 @@ func (store *LevelDB3Store) DeleteFolderChildren(ctx context.Context, fullpath w
|
||||
}
|
||||
iter.Release()
|
||||
|
||||
err = db.Write(batch, writeOptions(ctx))
|
||||
err = db.Write(batch, nil)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete %s : %v", fullpath, err)
|
||||
|
||||
@@ -2,8 +2,6 @@ package leveldb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
@@ -64,103 +62,6 @@ func TestCreateAndFind(t *testing.T) {
|
||||
|
||||
}
|
||||
|
||||
type fakeConfiguration map[string]interface{}
|
||||
|
||||
func (c fakeConfiguration) GetString(key string) string {
|
||||
value, _ := c[key].(string)
|
||||
return value
|
||||
}
|
||||
|
||||
func (c fakeConfiguration) GetBool(key string) bool {
|
||||
value, _ := c[key].(bool)
|
||||
return value
|
||||
}
|
||||
|
||||
func (c fakeConfiguration) GetInt(key string) int {
|
||||
value, _ := c[key].(int)
|
||||
return value
|
||||
}
|
||||
|
||||
func (c fakeConfiguration) GetStringSlice(key string) []string {
|
||||
value, _ := c[key].([]string)
|
||||
return value
|
||||
}
|
||||
|
||||
func (c fakeConfiguration) SetDefault(key string, value interface{}) {
|
||||
if _, found := c[key]; !found {
|
||||
c[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeOptions(t *testing.T) {
|
||||
store := &LevelDB3Store{}
|
||||
if err := store.Initialize(fakeConfiguration{
|
||||
"leveldb3.dir": t.TempDir(),
|
||||
"leveldb3.block_cache_size_mb": 64,
|
||||
"leveldb3.write_buffer_size_mb": 32,
|
||||
"leveldb3.block_size_kb": 16,
|
||||
"leveldb3.compaction_table_size_mb": 8,
|
||||
}, "leveldb3."); err != nil {
|
||||
t.Fatalf("initialize: %v", err)
|
||||
}
|
||||
defer store.Shutdown()
|
||||
|
||||
for _, name := range []string{DEFAULT, "bucket-a"} {
|
||||
opts := store.buildOptions(name)
|
||||
if opts.BlockCacheCapacity != 64*1024*1024 {
|
||||
t.Errorf("%s block cache %d, want 64MiB", name, opts.BlockCacheCapacity)
|
||||
}
|
||||
if opts.WriteBuffer != 32*1024*1024 {
|
||||
t.Errorf("%s write buffer %d, want 32MiB", name, opts.WriteBuffer)
|
||||
}
|
||||
if opts.BlockSize != 16*1024 {
|
||||
t.Errorf("%s block size %d, want 16KiB", name, opts.BlockSize)
|
||||
}
|
||||
if opts.CompactionTableSize != 8*1024*1024 {
|
||||
t.Errorf("%s compaction table size %d, want 8MiB", name, opts.CompactionTableSize)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeDefaultOptions(t *testing.T) {
|
||||
store := &LevelDB3Store{}
|
||||
if err := store.Initialize(fakeConfiguration{
|
||||
"leveldb3.dir": t.TempDir(),
|
||||
"leveldb3.block_cache_size_mb": -1,
|
||||
"leveldb3.write_buffer_size_mb": 0,
|
||||
}, "leveldb3."); err != nil {
|
||||
t.Fatalf("initialize: %v", err)
|
||||
}
|
||||
defer store.Shutdown()
|
||||
|
||||
opts := store.buildOptions(DEFAULT)
|
||||
if opts.BlockCacheCapacity != 32*1024*1024 {
|
||||
t.Errorf("block cache %d, want the 32MiB default", opts.BlockCacheCapacity)
|
||||
}
|
||||
if opts.WriteBuffer != 16*1024*1024 {
|
||||
t.Errorf("write buffer %d, want the 16MiB default", opts.WriteBuffer)
|
||||
}
|
||||
|
||||
bucketOpts := store.buildOptions("bucket-a")
|
||||
if bucketOpts.BlockCacheCapacity != 16*1024*1024 {
|
||||
t.Errorf("bucket block cache %d, want the 16MiB default", bucketOpts.BlockCacheCapacity)
|
||||
}
|
||||
if bucketOpts.WriteBuffer != 8*1024*1024 {
|
||||
t.Errorf("bucket write buffer %d, want the 8MiB default", bucketOpts.WriteBuffer)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeRejectsOversizedOption(t *testing.T) {
|
||||
store := &LevelDB3Store{}
|
||||
err := store.Initialize(fakeConfiguration{
|
||||
"leveldb3.dir": t.TempDir(),
|
||||
"leveldb3.write_buffer_size_mb": math.MaxInt/(1<<20) + 1,
|
||||
}, "leveldb3.")
|
||||
if err == nil || !strings.Contains(err.Error(), "write_buffer_size_mb") {
|
||||
t.Fatalf("expected overflow rejection, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyRoot(t *testing.T) {
|
||||
testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
|
||||
dir := t.TempDir()
|
||||
|
||||
@@ -62,15 +62,6 @@ func (gen *SqlGenMysql) nameExpr() string {
|
||||
return "`name`"
|
||||
}
|
||||
|
||||
// GetSqlScanPage spells the cursor as two primary-key ranges: MySQL 5.7 does
|
||||
// not turn a row-value comparison into a range seek. The name keeps the
|
||||
// column's own collation (BINARY would filesort every page); the scan promises
|
||||
// no lexical order. SQLite overrides this method.
|
||||
func (gen *SqlGenMysql) GetSqlScanPage(tableName string, dirhash int64, name string, limit int) (string, []interface{}) {
|
||||
return fmt.Sprintf("SELECT `dirhash`, `name`, `directory`, `meta` FROM `%s` WHERE `dirhash` > ? OR (`dirhash` = ? AND `name` > ?) ORDER BY `dirhash` ASC, `name` ASC LIMIT ?", tableName),
|
||||
[]interface{}{dirhash, dirhash, name, limit}
|
||||
}
|
||||
|
||||
func (gen *SqlGenMysql) GetSqlListExclusive(tableName string) string {
|
||||
name := gen.nameExpr()
|
||||
return fmt.Sprintf("SELECT `name`, `meta` FROM `%s` WHERE `dirhash` = ? AND %s > ? AND `directory` = ? AND %s LIKE ? ESCAPE '!' ORDER BY %s ASC LIMIT ?", tableName, name, name, name)
|
||||
|
||||
@@ -75,14 +75,6 @@ func (gen *SqlGenPostgres) nameExpr() string {
|
||||
return "name"
|
||||
}
|
||||
|
||||
// GetSqlScanPage uses a row-value comparison, one primary-key range seek on
|
||||
// PostgreSQL. The name keeps the column's own collation (COLLATE "C" would
|
||||
// sort every page); the scan promises no lexical order.
|
||||
func (gen *SqlGenPostgres) GetSqlScanPage(tableName string, dirhash int64, name string, limit int) (string, []interface{}) {
|
||||
return fmt.Sprintf(`SELECT dirhash, name, directory, meta FROM "%s" WHERE (dirhash, name) > ($1, $2) ORDER BY dirhash ASC, name ASC LIMIT $3`, tableName),
|
||||
[]interface{}{dirhash, name, limit}
|
||||
}
|
||||
|
||||
func (gen *SqlGenPostgres) GetSqlListExclusive(tableName string) string {
|
||||
name := gen.nameExpr()
|
||||
return fmt.Sprintf(`SELECT NAME, meta FROM "%s" WHERE dirhash=$1 AND %s>$2 AND directory=$3 AND %s like $4 ESCAPE '!' ORDER BY %s ASC LIMIT $5`, tableName, name, name, name)
|
||||
|
||||
@@ -30,31 +30,6 @@ func (store *SqliteStore) GetName() string {
|
||||
return "sqlite"
|
||||
}
|
||||
|
||||
// sqliteSqlGen is the MySQL generator with SQLite's own page cursor: SQLite
|
||||
// seeks a row-value comparison on the primary key but scans the OR form.
|
||||
type sqliteSqlGen struct {
|
||||
*mysql.SqlGenMysql
|
||||
}
|
||||
|
||||
func (gen sqliteSqlGen) GetSqlScanPage(tableName string, dirhash int64, name string, limit int) (string, []interface{}) {
|
||||
return fmt.Sprintf("SELECT `dirhash`, `name`, `directory`, `meta` FROM `%s` WHERE (`dirhash`, `name`) > (?, ?) ORDER BY `dirhash` ASC, `name` ASC LIMIT ?", tableName),
|
||||
[]interface{}{dirhash, name, limit}
|
||||
}
|
||||
|
||||
// ScanEntries offers the snapshot scan only in WAL mode: with a rollback
|
||||
// journal a long read transaction holds a shared lock and writers fail after
|
||||
// the busy timeout.
|
||||
func (store *SqliteStore) ScanEntries(ctx context.Context, dirPath util.FullPath, fn func(ctx context.Context, entry *filer.Entry) error) error {
|
||||
var mode string
|
||||
if err := store.DB.QueryRowContext(ctx, "PRAGMA journal_mode").Scan(&mode); err != nil {
|
||||
return fmt.Errorf("%w: journal_mode: %v", filer.ErrUnsupportedEntryScan, err)
|
||||
}
|
||||
if !strings.EqualFold(mode, "wal") {
|
||||
return fmt.Errorf("%w: sqlite journal_mode is %q, the scan needs wal", filer.ErrUnsupportedEntryScan, mode)
|
||||
}
|
||||
return store.AbstractSqlStore.ScanEntries(ctx, dirPath, fn)
|
||||
}
|
||||
|
||||
func (store *SqliteStore) Initialize(configuration util.Configuration, prefix string) (err error) {
|
||||
dbFile := configuration.GetString(prefix + "dbFile")
|
||||
createTable := `CREATE TABLE IF NOT EXISTS "%s" (
|
||||
@@ -94,11 +69,11 @@ func sqliteDSN(dbFile string) string {
|
||||
func (store *SqliteStore) initialize(dbFile, createTable, upsertQuery string) (err error) {
|
||||
|
||||
store.SupportBucketTable = true
|
||||
store.SqlGenerator = sqliteSqlGen{&mysql.SqlGenMysql{
|
||||
store.SqlGenerator = &mysql.SqlGenMysql{
|
||||
CreateTableSqlTemplate: createTable,
|
||||
DropTableSqlTemplate: "drop table if exists `%s`",
|
||||
UpsertQueryTemplate: upsertQuery,
|
||||
}}
|
||||
}
|
||||
|
||||
dsn := sqliteDSN(dbFile)
|
||||
|
||||
@@ -119,11 +94,6 @@ func (store *SqliteStore) initialize(dbFile, createTable, upsertQuery string) (e
|
||||
}, 1, 1, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
// The main pool is one connection, which a long scan must not hold.
|
||||
if store.ScanDB, err = sql.Open("sqlite", dsn); err != nil {
|
||||
return fmt.Errorf("open scan connection to %s: %v", dbFile, err)
|
||||
}
|
||||
store.ScanDB.SetMaxOpenConns(1)
|
||||
|
||||
if err = store.CreateTable(context.Background(), abstract_sql.DEFAULT_TABLE); err != nil {
|
||||
return fmt.Errorf("init table %s: %v", abstract_sql.DEFAULT_TABLE, err)
|
||||
|
||||
@@ -1,288 +0,0 @@
|
||||
//go:build (linux || darwin || windows) && sqlite
|
||||
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// A rename committed while a scan is running is seen under exactly one of its
|
||||
// names. The scan reads from one snapshot, so unlike a directory walk it can
|
||||
// neither miss the entry when it moves into a directory already listed, nor
|
||||
// count it twice when it moves into one not listed yet.
|
||||
func TestScanEntriesSeesConcurrentRenameExactlyOnce(t *testing.T) {
|
||||
dbFile := filepath.Join(t.TempDir(), "filer.db")
|
||||
reader := &SqliteStore{}
|
||||
if err := reader.initialize(dbFile, createTableSql, upsertQuerySql); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reader.Shutdown()
|
||||
// WAL lets the writer commit while the scan's read transaction is open.
|
||||
if _, err := reader.DB.Exec("PRAGMA journal_mode=WAL"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writer := &SqliteStore{}
|
||||
if err := writer.initialize(dbFile, createTableSql, upsertQuerySql); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer writer.Shutdown()
|
||||
|
||||
ctx := context.Background()
|
||||
mk := func(p string) *filer.Entry {
|
||||
return &filer.Entry{FullPath: util.FullPath(p), Attr: filer.Attr{Mode: 0644, Mtime: time.Now(), Crtime: time.Now()}}
|
||||
}
|
||||
for _, p := range []string{"/ckpt/a", "/ckpt/b", "/ckpt/tmp/x"} {
|
||||
if err := reader.InsertEntry(ctx, mk(p)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
defer func(n int) { abstract_sql.SetScanPageSizeForTest(n) }(abstract_sql.SetScanPageSizeForTest(2))
|
||||
|
||||
seen := map[string]int{}
|
||||
renamed := false
|
||||
err := reader.ScanEntries(ctx, "/", func(_ context.Context, e *filer.Entry) error {
|
||||
seen[string(e.FullPath)]++
|
||||
if renamed {
|
||||
return nil
|
||||
}
|
||||
renamed = true
|
||||
// /ckpt/tmp/x -> /ckpt/x, committed by another connection mid-scan.
|
||||
if err := writer.InsertEntry(ctx, mk("/ckpt/x")); err != nil {
|
||||
return err
|
||||
}
|
||||
return writer.DeleteEntry(ctx, util.FullPath("/ckpt/tmp/x"))
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !renamed {
|
||||
t.Fatal("scan yielded nothing")
|
||||
}
|
||||
if seen["/ckpt/a"] != 1 || seen["/ckpt/b"] != 1 {
|
||||
t.Errorf("untouched entries seen %d and %d times, want once each", seen["/ckpt/a"], seen["/ckpt/b"])
|
||||
}
|
||||
if old, new := seen["/ckpt/tmp/x"], seen["/ckpt/x"]; old+new != 1 {
|
||||
t.Errorf("renamed entry seen %d time(s) under the old name and %d under the new, want exactly one in total", old, new)
|
||||
} else if old != 1 {
|
||||
t.Errorf("the rename committed after the snapshot was taken, so the scan must show the old name")
|
||||
}
|
||||
if _, err := reader.FindEntry(ctx, util.FullPath("/ckpt/x")); err != nil {
|
||||
t.Errorf("once the scan is over the new name must be visible: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Rows that are not entries, key-value records and a regular file under
|
||||
// /buckets with a bucket-like name, are stepped over; a scan rooted at a bucket
|
||||
// yields the bucket's own row (default table) and its contents (bucket table).
|
||||
func TestScanEntriesRowsAndBucketTables(t *testing.T) {
|
||||
store := &SqliteStore{}
|
||||
if err := store.initialize(filepath.Join(t.TempDir(), "filer.db"), createTableSql, upsertQuerySql); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Shutdown()
|
||||
if _, err := store.DB.Exec("PRAGMA journal_mode=WAL"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
// The filer creates bucket tables on bucket creation; the store layer alone does not.
|
||||
if err := store.CreateTable(ctx, "realbucket"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, e := range []*filer.Entry{
|
||||
{FullPath: "/buckets", Attr: filer.Attr{Mode: 0755 | os.ModeDir, Mtime: now, Crtime: now}},
|
||||
{FullPath: "/buckets/realbucket", Attr: filer.Attr{Mode: 0755 | os.ModeDir, Mtime: now, Crtime: now}},
|
||||
{FullPath: "/buckets/realbucket/f1", Attr: filer.Attr{Mode: 0644, Mtime: now, Crtime: now}},
|
||||
{FullPath: "/buckets/readme", Attr: filer.Attr{Mode: 0644, Mtime: now, Crtime: now}},
|
||||
{FullPath: "/topics/t1", Attr: filer.Attr{Mode: 0644, Mtime: now, Crtime: now}},
|
||||
} {
|
||||
if err := store.InsertEntry(ctx, e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"filer.store.id", "/looks/like/a/path", "x"} {
|
||||
if err := store.KvPut(ctx, []byte(key), []byte("opaque value, not an Entry")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
collect := func(root string) []string {
|
||||
var got []string
|
||||
if err := store.ScanEntries(ctx, util.FullPath(root), func(_ context.Context, e *filer.Entry) error {
|
||||
got = append(got, string(e.FullPath))
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("scan %s: %v", root, err)
|
||||
}
|
||||
sort.Strings(got)
|
||||
return got
|
||||
}
|
||||
if got, want := collect("/"), []string{"/buckets", "/buckets/readme", "/buckets/realbucket", "/buckets/realbucket/f1", "/topics/t1"}; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("scan /: got %v, want %v", got, want)
|
||||
}
|
||||
if got, want := collect("/buckets/realbucket"), []string{"/buckets/realbucket", "/buckets/realbucket/f1"}; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("scan /buckets/realbucket: got %v, want %v", got, want)
|
||||
}
|
||||
|
||||
// A bucket directory whose table does not exist fails the scan: from the
|
||||
// snapshot it cannot be told from a table dropped a moment ago.
|
||||
if err := store.InsertEntry(ctx, &filer.Entry{FullPath: "/buckets/ghostbucket", Attr: filer.Attr{Mode: 0755 | os.ModeDir, Mtime: now, Crtime: now}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := store.ScanEntries(ctx, "/", func(context.Context, *filer.Entry) error { return nil })
|
||||
if err == nil || !strings.Contains(err.Error(), "ghostbucket") {
|
||||
t.Fatalf("scan over a bucket without a table must fail naming it, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Without WAL the store declines the scan rather than block writers for its
|
||||
// whole duration.
|
||||
func TestScanEntriesDeclinedWithoutWAL(t *testing.T) {
|
||||
store := &SqliteStore{}
|
||||
if err := store.initialize(filepath.Join(t.TempDir(), "filer.db"), createTableSql, upsertQuerySql); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Shutdown()
|
||||
err := store.ScanEntries(context.Background(), "/", func(context.Context, *filer.Entry) error { return nil })
|
||||
if !errors.Is(err, filer.ErrUnsupportedEntryScan) {
|
||||
t.Fatalf("err = %v, want ErrUnsupportedEntryScan", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A store whose pool is one connection, and no scan connection of its own,
|
||||
// declines rather than hold that connection for the whole scan.
|
||||
func TestScanEntriesDeclinedOnSingleConnectionPool(t *testing.T) {
|
||||
store := &SqliteStore{}
|
||||
if err := store.initialize(filepath.Join(t.TempDir(), "filer.db"), createTableSql, upsertQuerySql); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Shutdown()
|
||||
if _, err := store.DB.Exec("PRAGMA journal_mode=WAL"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store.ScanDB.Close()
|
||||
store.ScanDB = nil
|
||||
err := store.ScanEntries(context.Background(), "/", func(context.Context, *filer.Entry) error { return nil })
|
||||
if !errors.Is(err, filer.ErrUnsupportedEntryScan) {
|
||||
t.Fatalf("err = %v, want ErrUnsupportedEntryScan", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A hard-linked entry's chunks live in the shared key-value record, not in
|
||||
// its path row; the wrapper resolves them from inside the snapshot, on the
|
||||
// single connection the scan holds.
|
||||
func TestScanEntriesResolvesHardLinks(t *testing.T) {
|
||||
store := &SqliteStore{}
|
||||
if err := store.initialize(filepath.Join(t.TempDir(), "filer.db"), createTableSql, upsertQuerySql); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Shutdown()
|
||||
if _, err := store.DB.Exec("PRAGMA journal_mode=WAL"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wrapper := filer.NewFilerStoreWrapper(store)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
linked := &filer.Entry{
|
||||
FullPath: "/buckets/hlbucket/f0001",
|
||||
Attr: filer.Attr{Mode: 0644, Mtime: now, Crtime: now},
|
||||
HardLinkId: filer.HardLinkId("hardlink-00000001"),
|
||||
HardLinkCounter: 2,
|
||||
Chunks: []*filer_pb.FileChunk{{FileId: "3,01637037d6", Size: 4096}},
|
||||
}
|
||||
if err := wrapper.InsertEntry(ctx, linked); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var got *filer.Entry
|
||||
if err := wrapper.ScanEntries(ctx, "/", func(_ context.Context, e *filer.Entry) error {
|
||||
if e.FullPath == linked.FullPath {
|
||||
got = e
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got == nil || len(got.GetChunks()) != 1 || got.GetChunks()[0].FileId != "3,01637037d6" || got.HardLinkCounter != 2 {
|
||||
t.Fatalf("hard-linked entry not resolved from its key-value record: %+v", got)
|
||||
}
|
||||
|
||||
// Once the record is gone the path row is all there is; the scan hands it
|
||||
// over instead of failing on that entry every time it runs.
|
||||
if err := store.KvDelete(ctx, []byte(linked.HardLinkId)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = nil
|
||||
if err := wrapper.ScanEntries(ctx, "/", func(_ context.Context, e *filer.Entry) error {
|
||||
if e.FullPath == linked.FullPath {
|
||||
got = e
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("a missing hard-link record must not fail the scan: %v", err)
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatal("entry with a missing hard-link record not handed over")
|
||||
}
|
||||
}
|
||||
|
||||
// The keyset page must be a primary-key seek; an OR-shaped cursor predicate
|
||||
// makes SQLite scan the table from the start for every page.
|
||||
func TestScanPageQuerySeeksPrimaryKey(t *testing.T) {
|
||||
store := &SqliteStore{}
|
||||
if err := store.initialize(filepath.Join(t.TempDir(), "filer.db"), createTableSql, upsertQuerySql); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Shutdown()
|
||||
sqlText, args := store.GetSqlScanPage("filemeta", int64(-1), "", 10)
|
||||
rows, err := store.DB.Query("EXPLAIN QUERY PLAN "+sqlText, args...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var plan []string
|
||||
for rows.Next() {
|
||||
var id, parent, notused int
|
||||
var detail string
|
||||
if err := rows.Scan(&id, &parent, ¬used, &detail); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plan = append(plan, detail)
|
||||
}
|
||||
joined := strings.Join(plan, " | ")
|
||||
if !strings.Contains(joined, "SEARCH") || strings.Contains(joined, "SCAN") {
|
||||
t.Fatalf("page query does not seek the primary key: %s", joined)
|
||||
}
|
||||
}
|
||||
|
||||
// A bucket name only the process cache remembers may have its table dropped
|
||||
// meanwhile; the scan skips it instead of failing.
|
||||
func TestScanEntriesSkipsCachedOnlyBucketTable(t *testing.T) {
|
||||
store := &SqliteStore{}
|
||||
if err := store.initialize(filepath.Join(t.TempDir(), "filer.db"), createTableSql, upsertQuerySql); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Shutdown()
|
||||
if _, err := store.DB.Exec("PRAGMA journal_mode=WAL"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store.OnBucketCreation("gonebucket") // the table is never created
|
||||
if err := store.ScanEntries(context.Background(), "/", func(context.Context, *filer.Entry) error { return nil }); err != nil {
|
||||
t.Fatalf("cached-only bucket with a dropped table must not fail the scan: %v", err)
|
||||
}
|
||||
}
|
||||
+5
-8
@@ -98,13 +98,11 @@ var fineGrainedActionMap = map[string]string{
|
||||
// prefixed (s3:Action) and unprefixed (Action) variants in init().
|
||||
var baseS3ActionMap = map[string]string{
|
||||
// Object operations
|
||||
"DeleteObject": s3_constants.ACTION_WRITE,
|
||||
"PutObject": s3_constants.ACTION_WRITE,
|
||||
"GetObject": s3_constants.ACTION_READ,
|
||||
"DeleteObjectVersion": s3_constants.ACTION_WRITE,
|
||||
"GetObjectVersion": s3_constants.ACTION_READ,
|
||||
"GetObjectAttributes": s3_constants.ACTION_READ,
|
||||
"GetObjectVersionAttributes": s3_constants.ACTION_READ,
|
||||
"DeleteObject": s3_constants.ACTION_WRITE,
|
||||
"PutObject": s3_constants.ACTION_WRITE,
|
||||
"GetObject": s3_constants.ACTION_READ,
|
||||
"DeleteObjectVersion": s3_constants.ACTION_WRITE,
|
||||
"GetObjectVersion": s3_constants.ACTION_READ,
|
||||
// Tagging operations
|
||||
"GetObjectTagging": s3_constants.ACTION_TAGGING,
|
||||
"GetObjectVersionTagging": s3_constants.ACTION_TAGGING,
|
||||
@@ -117,7 +115,6 @@ var baseS3ActionMap = map[string]string{
|
||||
"DeleteBucketTagging": s3_constants.ACTION_TAGGING,
|
||||
// ACL operations
|
||||
"PutObjectAcl": s3_constants.ACTION_WRITE_ACP,
|
||||
"PutObjectVersionAcl": s3_constants.ACTION_WRITE_ACP,
|
||||
"GetObjectAcl": s3_constants.ACTION_READ_ACP,
|
||||
"GetObjectVersionAcl": s3_constants.ACTION_READ_ACP,
|
||||
"PutBucketAcl": s3_constants.ACTION_WRITE_ACP,
|
||||
|
||||
@@ -100,11 +100,6 @@ type STSSessionClaims struct {
|
||||
// guaranteed stable per OpenID Connect Core 1.0. Empty for non-federated
|
||||
// session types.
|
||||
ParentUser string `json:"puid,omitempty"`
|
||||
|
||||
// SourceAccessKeyId is the access key the caller authenticated with when
|
||||
// a SeaweedFS service minted the session for it (AssumeRoleForPrincipal);
|
||||
// empty for every other session type.
|
||||
SourceAccessKeyId string `json:"src_ak,omitempty"`
|
||||
}
|
||||
|
||||
// NewSTSSessionClaims creates new STS session claims with all required information
|
||||
@@ -161,8 +156,6 @@ func (c *STSSessionClaims) ToSessionInfo(credGen *CredentialGenerator) *SessionI
|
||||
ProviderIssuer: c.ProviderIssuer,
|
||||
RequestContext: c.RequestContext,
|
||||
ParentUser: c.ParentUser,
|
||||
// The access key the session was minted for, if recorded
|
||||
SourceAccessKeyId: c.SourceAccessKeyId,
|
||||
// Provide the Subject (sub) from registered claims
|
||||
Subject: c.Subject,
|
||||
Credentials: credentials,
|
||||
@@ -257,12 +250,6 @@ func (c *STSSessionClaims) WithSessionName(sessionName string) *STSSessionClaims
|
||||
return c
|
||||
}
|
||||
|
||||
// WithSourceAccessKeyId records the access key the session was minted for.
|
||||
func (c *STSSessionClaims) WithSourceAccessKeyId(accessKeyId string) *STSSessionClaims {
|
||||
c.SourceAccessKeyId = accessKeyId
|
||||
return c
|
||||
}
|
||||
|
||||
// WithParentUser sets the stable per-identity hash for the session. See
|
||||
// ComputeParentUser for the derivation rule.
|
||||
func (c *STSSessionClaims) WithParentUser(parentUser string) *STSSessionClaims {
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
package sts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newSourceKeyTestSTS(t *testing.T) *STSService {
|
||||
t.Helper()
|
||||
s := NewSTSService()
|
||||
require.NoError(t, s.Initialize(&STSConfig{
|
||||
TokenDuration: FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test-issuer",
|
||||
SigningKey: []byte("test-signing-key-at-least-32-bytes-long-for-security"),
|
||||
}))
|
||||
return s
|
||||
}
|
||||
|
||||
// A session minted for a caller's access key carries that key back out of its
|
||||
// token; a session minted without one carries none.
|
||||
func TestSessionCarriesItsSourceAccessKey(t *testing.T) {
|
||||
s := newSourceKeyTestSTS(t)
|
||||
resp, err := s.issueSession("arn:aws:iam::role/IcebergTableAccess", "", "iceberg-alice-ns-t-kabc", "", nil,
|
||||
"iceberg-catalog", "alice", func(c *STSSessionClaims) { c.WithSourceAccessKeyId("AKIASOURCE") })
|
||||
require.NoError(t, err)
|
||||
info, err := s.ValidateSessionToken(context.Background(), resp.Credentials.SessionToken)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "AKIASOURCE", info.SourceAccessKeyId)
|
||||
assert.Equal(t, "alice", info.ExternalUserId)
|
||||
assert.Equal(t, "iceberg-catalog", info.IdentityProvider)
|
||||
|
||||
resp, err = s.issueSession("arn:aws:iam::role/IcebergTableAccess", "", "iceberg-alice-ns-t", "", nil, "iceberg-catalog", "alice")
|
||||
require.NoError(t, err)
|
||||
info, err = s.ValidateSessionToken(context.Background(), resp.Credentials.SessionToken)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "", info.SourceAccessKeyId)
|
||||
}
|
||||
@@ -316,10 +316,6 @@ type SessionInfo struct {
|
||||
// RoleId is the unique ID of the role the session was issued for; empty
|
||||
// for sessions issued before role IDs were recorded.
|
||||
RoleId string `json:"roleId,omitempty"`
|
||||
|
||||
// SourceAccessKeyId is the access key the session was minted for, when the
|
||||
// minting service recorded it (AssumeRoleForPrincipal).
|
||||
SourceAccessKeyId string `json:"sourceAccessKeyId,omitempty"`
|
||||
}
|
||||
|
||||
// NewSTSService creates a new STS service
|
||||
@@ -784,7 +780,7 @@ func (s *STSService) AssumeRoleWithCredentials(ctx context.Context, request *Ass
|
||||
// issueSession mints temporary credentials and the self-contained JWT that
|
||||
// carries the whole session, shared by every assume-role entry point.
|
||||
func (s *STSService) issueSession(roleArn, roleId, roleSessionName, sessionPolicy string,
|
||||
durationSeconds *int64, providerName, subject string, options ...func(*STSSessionClaims)) (*AssumeRoleResponse, error) {
|
||||
durationSeconds *int64, providerName, subject string) (*AssumeRoleResponse, error) {
|
||||
|
||||
sessionDuration := s.CalculateSessionDuration(durationSeconds)
|
||||
expiresAt := time.Now().Add(sessionDuration)
|
||||
@@ -814,9 +810,6 @@ func (s *STSService) issueSession(roleArn, roleId, roleSessionName, sessionPolic
|
||||
if sessionPolicy != "" {
|
||||
sessionClaims.WithSessionPolicy(sessionPolicy)
|
||||
}
|
||||
for _, option := range options {
|
||||
option(sessionClaims)
|
||||
}
|
||||
|
||||
jwtToken, err := s.tokenGenerator.GenerateJWTWithClaims(sessionClaims)
|
||||
if err != nil {
|
||||
@@ -870,10 +863,6 @@ type AssumeRoleForPrincipalRequest struct {
|
||||
|
||||
// DurationSeconds requests a session lifetime.
|
||||
DurationSeconds *int64
|
||||
|
||||
// SourceAccessKeyId optionally records the access key the caller
|
||||
// authenticated with, so the session can be tied to that key.
|
||||
SourceAccessKeyId string
|
||||
}
|
||||
|
||||
// AssumeRoleForPrincipal issues session credentials for a caller that a
|
||||
@@ -919,8 +908,7 @@ func (s *STSService) AssumeRoleForPrincipal(ctx context.Context, request *Assume
|
||||
// Iceberg credential vending resolves no role definition, so its sessions
|
||||
// carry no role ID and stay bound by name.
|
||||
return s.issueSession(request.RoleArn, "", request.RoleSessionName, sessionPolicy,
|
||||
request.DurationSeconds, request.ProviderName, request.Principal,
|
||||
func(c *STSSessionClaims) { c.WithSourceAccessKeyId(request.SourceAccessKeyId) })
|
||||
request.DurationSeconds, request.ProviderName, request.Principal)
|
||||
}
|
||||
|
||||
// ValidateSessionToken validates a session token and returns session information
|
||||
|
||||
@@ -42,11 +42,10 @@ type IamS3ApiConfigure struct {
|
||||
}
|
||||
|
||||
type IamServerOption struct {
|
||||
Masters map[string]pb.ServerAddress
|
||||
Filers []pb.ServerAddress
|
||||
Port int
|
||||
GrpcDialOption grpc.DialOption
|
||||
IamSelfServiceRequiresGrant bool
|
||||
Masters map[string]pb.ServerAddress
|
||||
Filers []pb.ServerAddress
|
||||
Port int
|
||||
GrpcDialOption grpc.DialOption
|
||||
}
|
||||
|
||||
type IamApiServer struct {
|
||||
@@ -88,9 +87,8 @@ func NewIamApiServerWithStore(router *mux.Router, option *IamServerOption, expli
|
||||
s3ApiConfigure = configure
|
||||
|
||||
s3Option := s3api.S3ApiServerOption{
|
||||
Filers: option.Filers,
|
||||
GrpcDialOption: option.GrpcDialOption,
|
||||
IamSelfServiceRequiresGrant: option.IamSelfServiceRequiresGrant,
|
||||
Filers: option.Filers,
|
||||
GrpcDialOption: option.GrpcDialOption,
|
||||
}
|
||||
|
||||
// Initialize FilerClient for IAM - explicit filers only (no discovery as FilerGroup unspecified)
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
@@ -102,9 +101,6 @@ func readChunkNeedle(fileUrl string, w io.Writer, offset int64, jwt string) (wri
|
||||
if offset > 0 {
|
||||
req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset))
|
||||
}
|
||||
if jwt != "" {
|
||||
req.Header.Set("Authorization", security.BearerPrefix+jwt)
|
||||
}
|
||||
|
||||
resp, err := util_http.Do(req)
|
||||
if err != nil {
|
||||
@@ -122,7 +118,7 @@ func readChunkNeedle(fileUrl string, w io.Writer, offset int64, jwt string) (wri
|
||||
case http.StatusPartialContent:
|
||||
break
|
||||
default:
|
||||
return written, util_http.StatusError(fileUrl, resp)
|
||||
return written, fmt.Errorf("Read chunk needle error: [%d] %s", resp.StatusCode, fileUrl)
|
||||
|
||||
}
|
||||
return io.Copy(w, resp.Body)
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
|
||||
@@ -51,10 +50,6 @@ type StoragePreference struct {
|
||||
|
||||
type GetMasterFn func(ctx context.Context) pb.ServerAddress
|
||||
|
||||
// submitUploadWorkers bounds how many files one SubmitFiles call uploads at
|
||||
// once; the batch assign above already fetched all their file ids.
|
||||
const submitUploadWorkers = 4
|
||||
|
||||
func SubmitFiles(masterFn GetMasterFn, grpcDialOption grpc.DialOption, files []*FilePart, pref StoragePreference, usePublicUrl bool) ([]SubmitResult, error) {
|
||||
results := make([]SubmitResult, len(files))
|
||||
var totalBytes int64
|
||||
@@ -77,11 +72,8 @@ func SubmitFiles(masterFn GetMasterFn, grpcDialOption grpc.DialOption, files []*
|
||||
}
|
||||
ret, err := Assign(context.Background(), masterFn, grpcDialOption, ar)
|
||||
if err != nil {
|
||||
for index, file := range files {
|
||||
for index := range files {
|
||||
results[index].Error = err.Error()
|
||||
if closer, ok := file.Reader.(io.Closer); ok {
|
||||
closer.Close()
|
||||
}
|
||||
}
|
||||
return results, err
|
||||
}
|
||||
@@ -95,35 +87,14 @@ func SubmitFiles(masterFn GetMasterFn, grpcDialOption grpc.DialOption, files []*
|
||||
file.Server = ret.PublicUrl
|
||||
}
|
||||
file.Pref = pref
|
||||
results[index].Size, err = file.Upload(pref.MaxMB, masterFn, usePublicUrl, ret.Auth, grpcDialOption)
|
||||
if err != nil {
|
||||
results[index].Error = err.Error()
|
||||
}
|
||||
results[index].Fid = file.Fid
|
||||
results[index].FileUrl = ret.PublicUrl + "/" + file.Fid
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
var lastErrLock sync.Mutex
|
||||
jobs := make(chan int)
|
||||
for w := 0; w < min(submitUploadWorkers, len(files)); w++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for index := range jobs {
|
||||
size, uploadErr := files[index].Upload(pref.MaxMB, masterFn, usePublicUrl, ret.Auth, grpcDialOption)
|
||||
results[index].Size = size
|
||||
if uploadErr != nil {
|
||||
results[index].Error = uploadErr.Error()
|
||||
lastErrLock.Lock()
|
||||
err = uploadErr
|
||||
lastErrLock.Unlock()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
for index := range files {
|
||||
jobs <- index
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
return results, err
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func NewFileParts(fullPathFilenames []string) (ret []*FilePart, err error) {
|
||||
@@ -147,8 +118,6 @@ func newFilePart(fullPathFilename string) (ret *FilePart, err error) {
|
||||
fi, fiErr := fh.Stat()
|
||||
if fiErr != nil {
|
||||
glog.V(0).Info("Failed to stat file:", fullPathFilename)
|
||||
fh.Close()
|
||||
ret.Reader = nil
|
||||
return ret, fiErr
|
||||
}
|
||||
ret.ModTime = fi.ModTime().UTC().Unix()
|
||||
|
||||
@@ -67,16 +67,6 @@ func GetEntry(ctx context.Context, filerClient FilerClient, fullFilePath util.Fu
|
||||
// consumers would mistake for an entry.
|
||||
const ListSnapshotTsNsTrailerKey = "sw-list-snapshot-ts-ns"
|
||||
|
||||
// TraverseModeHeaderKey is gRPC metadata on a TraverseBfsMetadata stream. As
|
||||
// request metadata, TraverseModeSnapshot asks for the entries from one store
|
||||
// snapshot (any order, entry_ts_ns left 0) instead of a breadth-first walk; as
|
||||
// a response header it says what the filer did. An older filer sends none.
|
||||
const (
|
||||
TraverseModeHeaderKey = "sw-traverse-mode"
|
||||
TraverseModeSnapshot = "snapshot"
|
||||
TraverseModeBfs = "bfs"
|
||||
)
|
||||
|
||||
type EachEntryFunction func(entry *Entry, isLast bool) error
|
||||
|
||||
func ReadDirAllEntries(ctx context.Context, filerClient FilerClient, fullDirPath util.FullPath, prefix string, fn EachEntryFunction) (err error) {
|
||||
|
||||
@@ -168,27 +168,6 @@ func S3CompatibleEndpoint(conf *remote_pb.RemoteConf) (string, bool) {
|
||||
return opt.endpoint, true
|
||||
}
|
||||
|
||||
// awsCredentialSourceConfigured reports whether the environment names a source
|
||||
// for the AWS SDK default credential chain, such as static keys, a profile,
|
||||
// IRSA web identity or the ECS/EKS container credentials endpoint.
|
||||
func awsCredentialSourceConfigured() bool {
|
||||
for _, name := range []string{
|
||||
"AWS_ACCESS_KEY_ID",
|
||||
"AWS_PROFILE",
|
||||
"AWS_DEFAULT_PROFILE",
|
||||
"AWS_WEB_IDENTITY_TOKEN_FILE",
|
||||
"AWS_CONTAINER_CREDENTIALS_FULL_URI",
|
||||
"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
|
||||
"AWS_SHARED_CREDENTIALS_FILE",
|
||||
"AWS_CONFIG_FILE",
|
||||
} {
|
||||
if os.Getenv(name) != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// MakeWithHTTPClient builds the client for any S3-SDK-backed remote storage
|
||||
// type using the supplied *http.Client (or the AWS SDK default when nil).
|
||||
// Callers that need to pin the dial path against DNS rebinding can pass a
|
||||
@@ -212,32 +191,12 @@ func MakeWithHTTPClient(conf *remote_pb.RemoteConf, httpClient *http.Client) (re
|
||||
}
|
||||
if opt.accessKey != "" && opt.secretKey != "" {
|
||||
config.Credentials = credentials.NewStaticCredentials(opt.accessKey, opt.secretKey, "")
|
||||
} else if opt.anonymousWhenNoCreds && opt.accessKey == "" && opt.secretKey == "" && !awsCredentialSourceConfigured() {
|
||||
// Explicitly disable signing for public buckets. When the environment
|
||||
// names an AWS credential source, leave Credentials nil so the SDK
|
||||
// default chain (env, web identity, container, shared profile) is used.
|
||||
} else if opt.anonymousWhenNoCreds && opt.accessKey == "" && opt.secretKey == "" {
|
||||
// Explicitly disable signing for public buckets.
|
||||
config.Credentials = credentials.AnonymousCredentials
|
||||
} else if config.Credentials == nil && config.HTTPClient != nil {
|
||||
// Remote credential providers (container endpoints, IMDS, web
|
||||
// identity) fetch through this HTTP client; the guarded one is for the
|
||||
// S3 endpoint and blocks the link-local credential endpoints, so the
|
||||
// default chain resolves on an unguarded client. Shared config stays
|
||||
// enabled so web identity and profiles resolve here too, and the
|
||||
// region carries over so STS can sign assume-role requests.
|
||||
credSess, err := session.NewSessionWithOptions(session.Options{
|
||||
Config: aws.Config{Region: config.Region, HTTPClient: &http.Client{}},
|
||||
SharedConfigState: session.SharedConfigEnable,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create %s credential session: %w", opt.name, err)
|
||||
}
|
||||
config.Credentials = credSess.Config.Credentials
|
||||
}
|
||||
|
||||
sess, err := session.NewSessionWithOptions(session.Options{
|
||||
Config: *config,
|
||||
SharedConfigState: session.SharedConfigEnable,
|
||||
})
|
||||
sess, err := session.NewSession(config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create %s session: %w", opt.name, err)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ import (
|
||||
)
|
||||
|
||||
func TestS3MakeUsesAnonymousCredentialsWhenKeysAreEmpty(t *testing.T) {
|
||||
clearAWSCredentialEnv(t)
|
||||
maker := s3RemoteStorageMaker{}
|
||||
conf := &remote_pb.RemoteConf{
|
||||
Type: "s3",
|
||||
@@ -41,74 +40,6 @@ func TestS3MakeUsesAnonymousCredentialsWhenKeysAreEmpty(t *testing.T) {
|
||||
require.Same(t, credentials.AnonymousCredentials, s3Client.Config.Credentials)
|
||||
}
|
||||
|
||||
func clearAWSCredentialEnv(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, name := range []string{
|
||||
"AWS_ACCESS_KEY_ID",
|
||||
"AWS_PROFILE",
|
||||
"AWS_DEFAULT_PROFILE",
|
||||
"AWS_WEB_IDENTITY_TOKEN_FILE",
|
||||
"AWS_CONTAINER_CREDENTIALS_FULL_URI",
|
||||
"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
|
||||
"AWS_SHARED_CREDENTIALS_FILE",
|
||||
"AWS_CONFIG_FILE",
|
||||
} {
|
||||
t.Setenv(name, "")
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3MakeUsesDefaultCredentialChainWhenKeysAreEmptyAndSourceIsConfigured(t *testing.T) {
|
||||
for name, value := range map[string]string{
|
||||
"AWS_ACCESS_KEY_ID": "env-access",
|
||||
"AWS_PROFILE": "some-profile",
|
||||
"AWS_WEB_IDENTITY_TOKEN_FILE": "/var/run/secrets/token",
|
||||
"AWS_CONTAINER_CREDENTIALS_FULL_URI": "http://127.0.0.1:1/creds",
|
||||
"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI": "/creds",
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
clearAWSCredentialEnv(t)
|
||||
t.Setenv(name, value)
|
||||
t.Setenv("AWS_ROLE_ARN", "arn:aws:iam::123456789012:role/test")
|
||||
|
||||
remoteClient, err := s3RemoteStorageMaker{}.Make(&remote_pb.RemoteConf{
|
||||
Type: "s3",
|
||||
S3Region: "us-east-1",
|
||||
S3Endpoint: "http://localhost:8333",
|
||||
S3ForcePathStyle: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
s3Client, ok := remoteClient.(*s3RemoteStorageClient).conn.(*awss3.S3)
|
||||
require.True(t, ok)
|
||||
require.NotSame(t, credentials.AnonymousCredentials, s3Client.Config.Credentials)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A caller that pins a custom http.Client still gets the default chain, so
|
||||
// remote providers resolve on an unguarded client while S3 requests use the
|
||||
// pinned one.
|
||||
func TestS3MakeResolvesEnvCredentialsWithCustomHTTPClient(t *testing.T) {
|
||||
clearAWSCredentialEnv(t)
|
||||
t.Setenv("AWS_ACCESS_KEY_ID", "env-access")
|
||||
t.Setenv("AWS_SECRET_ACCESS_KEY", "env-secret")
|
||||
|
||||
remoteClient, err := MakeWithHTTPClient(&remote_pb.RemoteConf{
|
||||
Type: "s3",
|
||||
S3Region: "us-east-1",
|
||||
S3Endpoint: "http://localhost:8333",
|
||||
S3ForcePathStyle: true,
|
||||
}, &http.Client{})
|
||||
require.NoError(t, err)
|
||||
|
||||
s3Client, ok := remoteClient.(*s3RemoteStorageClient).conn.(*awss3.S3)
|
||||
require.True(t, ok)
|
||||
require.NotSame(t, credentials.AnonymousCredentials, s3Client.Config.Credentials)
|
||||
value, err := s3Client.Config.Credentials.Get()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "env-access", value.AccessKeyID)
|
||||
}
|
||||
|
||||
func TestS3MakeUsesStaticCredentialsWhenKeysAreProvided(t *testing.T) {
|
||||
maker := s3RemoteStorageMaker{}
|
||||
conf := &remote_pb.RemoteConf{
|
||||
@@ -465,24 +396,3 @@ func TestIsNoSuchKey(t *testing.T) {
|
||||
require.True(t, isNoSuchKey(fmt.Errorf("download: %w", awserr.New(awss3.ErrCodeNoSuchKey, "missing", nil))))
|
||||
require.False(t, isNoSuchKey(awserr.New(awss3.ErrCodeNoSuchBucket, "missing", nil)))
|
||||
}
|
||||
|
||||
func TestS3MakeResolvesEnvCredentialsWhenAnonymousDefault(t *testing.T) {
|
||||
clearAWSCredentialEnv(t)
|
||||
t.Setenv("AWS_ACCESS_KEY_ID", "env-access")
|
||||
t.Setenv("AWS_SECRET_ACCESS_KEY", "env-secret")
|
||||
|
||||
remoteClient, err := s3RemoteStorageMaker{}.Make(&remote_pb.RemoteConf{
|
||||
Type: "s3",
|
||||
S3Region: "us-east-1",
|
||||
S3Endpoint: "http://localhost:8333",
|
||||
S3ForcePathStyle: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
s3Client, ok := remoteClient.(*s3RemoteStorageClient).conn.(*awss3.S3)
|
||||
require.True(t, ok)
|
||||
value, err := s3Client.Config.Credentials.Get()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "env-access", value.AccessKeyID)
|
||||
require.Equal(t, "env-secret", value.SecretAccessKey)
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
const (
|
||||
sharedKeyA = "AKIASHAREDKEYAAAAAAA"
|
||||
sharedSecretA = "secret-a-wJalrXUtnFEMI/K7MDENG/bPxRfiCY"
|
||||
sharedKeyB = "AKIASHAREDKEYBBBBBBB"
|
||||
sharedSecretB = "secret-b-wJalrXUtnFEMI/K7MDENG/bPxRfiCY"
|
||||
)
|
||||
|
||||
// newSharedIdentityIAM returns one identity holding two key pairs, as when
|
||||
// several people or services are given their own key on one identity.
|
||||
func newSharedIdentityIAM() *IdentityAccessManagement {
|
||||
iam := &IdentityAccessManagement{}
|
||||
shared := &Identity{
|
||||
Name: "shared-user",
|
||||
Credentials: []*Credential{
|
||||
{AccessKey: sharedKeyA, SecretKey: sharedSecretA},
|
||||
{AccessKey: sharedKeyB, SecretKey: sharedSecretB},
|
||||
},
|
||||
Actions: []Action{s3_constants.ACTION_READ},
|
||||
}
|
||||
iam.identities = []*Identity{shared}
|
||||
iam.accessKeyIdent = map[string]*Identity{sharedKeyA: shared, sharedKeyB: shared}
|
||||
iam.nameToIdentity = map[string]*Identity{shared.Name: shared}
|
||||
return iam
|
||||
}
|
||||
|
||||
// Two keys of one identity: the audit entry names the same requester for both
|
||||
// and tells them apart by the key each request was signed with.
|
||||
func TestAuditLogCarriesTheSigningAccessKey(t *testing.T) {
|
||||
iam := newSharedIdentityIAM()
|
||||
for _, key := range []struct{ id, secret string }{{sharedKeyA, sharedSecretA}, {sharedKeyB, sharedSecretB}} {
|
||||
req, err := newTestRequest(http.MethodGet, "https://example.com/bucket/ns/t/data/f.parquet", 0, nil)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, signRequestV4(req, key.id, key.secret))
|
||||
// track() installs the holder before authentication runs.
|
||||
outer := s3_constants.EnsureIdentityHolder(req)
|
||||
|
||||
identity, errCode := iam.reqSignatureV4Verify(outer)
|
||||
require.Equal(t, s3err.ErrNone, errCode)
|
||||
iam.handleAuthResult(httptest.NewRecorder(), outer, identity, s3err.ErrNone, func(http.ResponseWriter, *http.Request) {})
|
||||
|
||||
log := s3err.GetAccessLog(outer, http.StatusOK, s3err.ErrNone)
|
||||
assert.Equal(t, "shared-user", log.Requester)
|
||||
assert.Equal(t, key.id, log.AccessKeyId, "audit entry must name the key the request was signed with")
|
||||
}
|
||||
}
|
||||
|
||||
// A request refused after authentication still names its key, like its requester.
|
||||
func TestAuditLogCarriesTheAccessKeyOnTheDenyPath(t *testing.T) {
|
||||
iam := newSharedIdentityIAM()
|
||||
req, err := newTestRequest(http.MethodGet, "https://example.com/bucket/f.parquet", 0, nil)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, signRequestV4(req, sharedKeyB, sharedSecretB))
|
||||
outer := s3_constants.EnsureIdentityHolder(req)
|
||||
identity, errCode := iam.reqSignatureV4Verify(outer)
|
||||
require.Equal(t, s3err.ErrNone, errCode)
|
||||
|
||||
iam.handleAuthResult(httptest.NewRecorder(), outer, identity, s3err.ErrAccessDenied, func(http.ResponseWriter, *http.Request) {
|
||||
t.Fatal("handler must not run on the deny path")
|
||||
})
|
||||
assert.Equal(t, sharedKeyB, s3err.GetAccessLog(outer, http.StatusForbidden, s3err.ErrAccessDenied).AccessKeyId)
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// signedPostFormV2 builds a multipart POST Object request whose policy is
|
||||
// signed with SigV2 under postAuthzAccessKey and secret.
|
||||
func signedPostFormV2(t *testing.T, key, secret string) *http.Request {
|
||||
t.Helper()
|
||||
policyJSON := fmt.Sprintf(`{"expiration":"%s","conditions":[["eq","$bucket","%s"],["eq","$key","%s"]]}`,
|
||||
time.Now().UTC().Add(time.Hour).Format("2006-01-02T15:04:05.000Z"), postAuthzBucket, key)
|
||||
encodedPolicy := base64.StdEncoding.EncodeToString([]byte(policyJSON))
|
||||
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
for _, field := range [][2]string{{"bucket", postAuthzBucket}, {"key", key}, {"AWSAccessKeyId", postAuthzAccessKey},
|
||||
{"policy", encodedPolicy}, {"Signature", calculateSignatureV2(encodedPolicy, secret)}} {
|
||||
require.NoError(t, writer.WriteField(field[0], field[1]))
|
||||
}
|
||||
filePart, err := writer.CreateFormFile("file", "payload.txt")
|
||||
require.NoError(t, err)
|
||||
_, err = filePart.Write([]byte("payload"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, writer.Close())
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/"+postAuthzBucket, &buf)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
return mux.SetURLVars(req, map[string]string{"bucket": postAuthzBucket})
|
||||
}
|
||||
|
||||
// A browser POST upload is verified in the handler from its form fields; the
|
||||
// key of the verified form reaches the audit log like a signed PUT's. The
|
||||
// bucket policy denies denied/ so the request ends before the filer.
|
||||
func TestPostPolicyUploadRecordsTheSigningKey(t *testing.T) {
|
||||
s3a := newPostAuthzServer(t)
|
||||
for name, req := range map[string]*http.Request{
|
||||
"SigV4": newSignedPostRequest(t, "denied/secret.txt"),
|
||||
"SigV2": signedPostFormV2(t, "denied/secret.txt", postAuthzSecretKey),
|
||||
} {
|
||||
outer := s3_constants.EnsureIdentityHolder(req)
|
||||
rec := httptest.NewRecorder()
|
||||
s3a.PostPolicyBucketHandler(rec, outer)
|
||||
require.Equal(t, http.StatusForbidden, rec.Code, "%s: %s", name, rec.Body.String())
|
||||
assert.Equal(t, postAuthzAccessKey, s3err.GetAccessLog(outer, http.StatusForbidden, s3err.ErrAccessDenied).AccessKeyId, name)
|
||||
}
|
||||
|
||||
// A form whose signature does not verify records nothing.
|
||||
outer := s3_constants.EnsureIdentityHolder(signedPostFormV2(t, "denied/secret.txt", "not-the-secret"))
|
||||
rec := httptest.NewRecorder()
|
||||
s3a.PostPolicyBucketHandler(rec, outer)
|
||||
require.Contains(t, rec.Body.String(), "SignatureDoesNotMatch")
|
||||
assert.Equal(t, "", s3_constants.GetAccessKeyIdFromContext(outer))
|
||||
}
|
||||
|
||||
// A signature that verifies for one virtual-hosted bucket but is routed to
|
||||
// another is refused after verification; the refusal still names the key.
|
||||
func TestSignedVirtualHostRetargetRecordsTheSigningKey(t *testing.T) {
|
||||
iam := newVirtualHostTestIAM("s3.test")
|
||||
r, err := newTestRequest("GET", "http://alpha-bkt.s3.test/shared.txt", 0, nil)
|
||||
require.NoError(t, err)
|
||||
r.Header.Set("Host", "alpha-bkt.s3.test")
|
||||
signV4WithPath(r, "access_key_1", "secret_key_1", r.URL.Path)
|
||||
r.Host = "beta-bkt.s3.test"
|
||||
r.Header.Set("X-Forwarded-Host", "alpha-bkt.s3.test")
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": "beta-bkt", "object": "shared.txt"})
|
||||
r = s3_constants.EnsureIdentityHolder(r)
|
||||
|
||||
_, _, errCode := iam.doesSignatureMatch(r)
|
||||
require.Equal(t, s3err.ErrAccessDenied, errCode)
|
||||
assert.Equal(t, "access_key_1", s3_constants.GetAccessKeyIdFromContext(r))
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// The key recorded for a request is the key of the credential that verified,
|
||||
// whatever else the request carries. A request names its key in several
|
||||
// places (SigV4 header, X-Amz-Credential, SigV2 header, AWSAccessKeyId);
|
||||
// getRequestAuthType picks one and that verifier records it, so a second,
|
||||
// unverified key in another place never reaches the audit log or a vended
|
||||
// session.
|
||||
|
||||
func authAndRecordedKey(t *testing.T, iam *IdentityAccessManagement, r *http.Request) (s3err.ErrorCode, string) {
|
||||
t.Helper()
|
||||
r = s3_constants.EnsureIdentityHolder(r)
|
||||
_, errCode, _ := iam.authenticateRequestInternal(r)
|
||||
return errCode, s3_constants.GetAccessKeyIdFromContext(r)
|
||||
}
|
||||
|
||||
func credOf(key, secret string) *Credential { return &Credential{AccessKey: key, SecretKey: secret} }
|
||||
|
||||
func TestRecordedKeyIsTheVerifiedKeyForSigV4Header(t *testing.T) {
|
||||
iam := newSharedIdentityIAM()
|
||||
r, err := newTestRequest(http.MethodGet, "https://example.com/bucket/f.parquet", 0, nil)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, signRequestV4(r, sharedKeyA, sharedSecretA))
|
||||
errCode, got := authAndRecordedKey(t, iam, r)
|
||||
require.Equal(t, s3err.ErrNone, errCode)
|
||||
assert.Equal(t, sharedKeyA, got)
|
||||
}
|
||||
|
||||
// SigV2 header signed with A, plus X-Amz-Credential naming B or garbage: the
|
||||
// request authenticates as A (SigV2 is checked first) and A is recorded.
|
||||
func TestRecordedKeyIgnoresAJunkCredentialQueryOnASigV2Request(t *testing.T) {
|
||||
iam := newSharedIdentityIAM()
|
||||
for _, junk := range []string{sharedKeyB + "/20261016/us-east-1/s3/aws4_request", "GARBAGE"} {
|
||||
r, err := http.NewRequest(http.MethodGet, "http://example.com/bucket/f.parquet?X-Amz-Credential="+url.QueryEscape(junk), nil)
|
||||
require.NoError(t, err)
|
||||
r.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
|
||||
r.Header.Set("Authorization", signatureV2(credOf(sharedKeyA, sharedSecretA), r.Method, r.URL.EscapedPath(), r.URL.Query().Encode(), r.Header))
|
||||
errCode, got := authAndRecordedKey(t, iam, r)
|
||||
require.Equal(t, s3err.ErrNone, errCode, "the SigV2 signature with A verifies (junk %q)", junk)
|
||||
assert.Equal(t, sharedKeyA, got, "the key that verified, not the junk %q", junk)
|
||||
}
|
||||
}
|
||||
|
||||
// SigV2 presigned with A, plus a junk SigV4 Authorization naming B: the
|
||||
// presigned A verifies and A is recorded.
|
||||
func TestRecordedKeyIgnoresAJunkSigV4HeaderOnASigV2PresignedRequest(t *testing.T) {
|
||||
iam := newSharedIdentityIAM()
|
||||
expires := strconv.FormatInt(time.Now().Add(10*time.Minute).Unix(), 10)
|
||||
q := url.Values{"AWSAccessKeyId": {sharedKeyA}, "Expires": {expires}}
|
||||
r, err := http.NewRequest(http.MethodGet, "http://example.com/bucket/f.parquet?"+q.Encode(), nil)
|
||||
require.NoError(t, err)
|
||||
sig := preSignatureV2(credOf(sharedKeyA, sharedSecretA), r.Method, r.URL.EscapedPath(), r.URL.Query().Encode(), r.Header, expires)
|
||||
q.Set("Signature", sig)
|
||||
r.URL.RawQuery = q.Encode()
|
||||
r.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential="+sharedKeyB+"/20261016/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=00")
|
||||
|
||||
errCode, got := authAndRecordedKey(t, iam, r)
|
||||
require.Equal(t, s3err.ErrNone, errCode, "the SigV2 presigned A verifies (SigV2 is dispatched first)")
|
||||
assert.Equal(t, sharedKeyA, got, "the presigned key A is recorded, never the unverified B")
|
||||
}
|
||||
|
||||
// A refused signature records nothing, even when the key exists.
|
||||
func TestRecordedKeyIsEmptyWhenTheSignatureFails(t *testing.T) {
|
||||
iam := newSharedIdentityIAM()
|
||||
r, err := newTestRequest(http.MethodGet, "https://example.com/bucket/f.parquet", 0, nil)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, signRequestV4(r, sharedKeyA, "not-the-secret"))
|
||||
errCode, got := authAndRecordedKey(t, iam, r)
|
||||
require.NotEqual(t, s3err.ErrNone, errCode)
|
||||
assert.Equal(t, "", got)
|
||||
|
||||
r2 := httptest.NewRequest(http.MethodGet, "http://example.com/bucket/f.parquet", nil)
|
||||
r2.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
|
||||
r2.Header.Set("Authorization", "AWS "+sharedKeyB+":bm90LWEtc2lnbmF0dXJl")
|
||||
errCode, got = authAndRecordedKey(t, iam, r2)
|
||||
require.NotEqual(t, s3err.ErrNone, errCode)
|
||||
assert.Equal(t, "", got)
|
||||
}
|
||||
|
||||
// A streaming (aws-chunked) upload records the key of its seed signature.
|
||||
func TestRecordedKeyForAStreamingUpload(t *testing.T) {
|
||||
iam := newSharedIdentityIAM()
|
||||
now := time.Now().UTC()
|
||||
amzDate, dateStamp := now.Format(iso8601Format), now.Format(yyyymmdd)
|
||||
scope := dateStamp + "/us-east-1/s3/aws4_request"
|
||||
hashedPayload := "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"
|
||||
canonicalHeaders := "content-encoding:aws-chunked\n" + "host:s3.amazonaws.com\n" +
|
||||
"x-amz-content-sha256:" + hashedPayload + "\n" + "x-amz-date:" + amzDate + "\n" + "x-amz-decoded-content-length:4\n"
|
||||
signedHeaders := "content-encoding;host;x-amz-content-sha256;x-amz-date;x-amz-decoded-content-length"
|
||||
canonicalRequest := "PUT\n/bucket/ns/t/data/f.parquet\n\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + hashedPayload
|
||||
stringToSign := "AWS4-HMAC-SHA256\n" + amzDate + "\n" + scope + "\n" + getSHA256Hash([]byte(canonicalRequest))
|
||||
seed := getSignature(getSigningKey(sharedSecretB, dateStamp, "us-east-1", "s3"), stringToSign)
|
||||
|
||||
r, err := http.NewRequest(http.MethodPut, "http://s3.amazonaws.com/bucket/ns/t/data/f.parquet", bytes.NewReader([]byte("ignored")))
|
||||
require.NoError(t, err)
|
||||
r.Header.Set("Host", "s3.amazonaws.com")
|
||||
r.Header.Set("x-amz-date", amzDate)
|
||||
r.Header.Set("x-amz-content-sha256", hashedPayload)
|
||||
r.Header.Set("Content-Encoding", "aws-chunked")
|
||||
r.Header.Set("x-amz-decoded-content-length", "4")
|
||||
r.Header.Set("Authorization", fmt.Sprintf("AWS4-HMAC-SHA256 Credential=%s/%s, SignedHeaders=%s, Signature=%s", sharedKeyB, scope, signedHeaders, seed))
|
||||
|
||||
errCode, got := authAndRecordedKey(t, iam, r)
|
||||
require.Equal(t, s3err.ErrNone, errCode)
|
||||
assert.Equal(t, sharedKeyB, got)
|
||||
}
|
||||
|
||||
// An STS session's request records the session's temporary key.
|
||||
func TestRecordedKeyForAnSTSSession(t *testing.T) {
|
||||
stsService, config := setupTestSTSService(t)
|
||||
iam := NewIdentityAccessManagementWithStore(&S3ApiServerOption{}, nil, "memory")
|
||||
iam.SetIAMIntegration(&S3IAMIntegration{stsService: stsService, enabled: true})
|
||||
sessionInfo, sessionToken := issueTestSession(t, stsService, config)
|
||||
|
||||
r, err := newTestRequest(http.MethodGet, "https://example.com/reports/data.csv", 0, nil)
|
||||
require.NoError(t, err)
|
||||
r.Header.Set("X-Amz-Security-Token", sessionToken)
|
||||
require.NoError(t, signRequestV4(r, sessionInfo.Credentials.AccessKeyId, sessionInfo.Credentials.SecretAccessKey))
|
||||
outer := s3_constants.EnsureIdentityHolder(r)
|
||||
identity, errCode := iam.reqSignatureV4Verify(outer)
|
||||
require.Equal(t, s3err.ErrNone, errCode)
|
||||
iam.handleAuthResult(httptest.NewRecorder(), outer, identity, s3err.ErrNone, func(http.ResponseWriter, *http.Request) {})
|
||||
assert.Equal(t, sessionInfo.Credentials.AccessKeyId, s3err.GetAccessLog(outer, http.StatusOK, s3err.ErrNone).AccessKeyId)
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package s3api
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -252,10 +251,9 @@ func TestAuthorizeCopySource_PresignedURLSessionTokenPreserved(t *testing.T) {
|
||||
}
|
||||
|
||||
// Presigned URL: session token is in the query string, no
|
||||
// X-Amz-Security-Token header. The destination URL also carries the rest of
|
||||
// the SigV4 presign params, which ride along so auth-derived policy
|
||||
// conditions (s3:authType) match the real request; none of them steer
|
||||
// ResolveS3Action.
|
||||
// X-Amz-Security-Token header. The destination URL also carries unrelated
|
||||
// SigV4 query params (X-Amz-Algorithm, etc.) that must not leak into the
|
||||
// synthetic source action resolution.
|
||||
req, err := http.NewRequest(http.MethodPut,
|
||||
"http://s3.local/bucket-a/dst.bin?X-Amz-Algorithm=AWS4-HMAC-SHA256"+
|
||||
"&X-Amz-Credential=stsKey%2F20260518%2Fus-east-1%2Fs3%2Faws4_request"+
|
||||
@@ -269,12 +267,8 @@ func TestAuthorizeCopySource_PresignedURLSessionTokenPreserved(t *testing.T) {
|
||||
assert.Equal(t, s3err.ErrNone, errCode)
|
||||
assert.Equal(t, "presigned-session-token", capturedSessionToken,
|
||||
"session token from presigned-URL query must reach the IAM check")
|
||||
capturedQuery, err := url.ParseQuery(capturedRawQuery)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "presigned-session-token", capturedQuery.Get("X-Amz-Security-Token"))
|
||||
assert.Equal(t, "AWS4-HMAC-SHA256", capturedQuery.Get("X-Amz-Algorithm"))
|
||||
assert.False(t, capturedQuery.Has("versionId"))
|
||||
assert.False(t, capturedQuery.Has("acl"))
|
||||
// versionId omitted, only the token should be present in the synthetic query.
|
||||
assert.Equal(t, "X-Amz-Security-Token=presigned-session-token", capturedRawQuery)
|
||||
}
|
||||
|
||||
// TestAuthorizeCopySource_PreservesCopySourceHeader verifies that the synthetic
|
||||
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3bucket"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/wildcard"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
@@ -69,11 +68,6 @@ type IdentityAccessManagement struct {
|
||||
// IAM Integration for advanced features
|
||||
iamIntegration IAMIntegration
|
||||
|
||||
// selfServiceRequiresGrant makes the self-service IAM actions (an
|
||||
// identity's own access keys, GetUser on itself) need an iam:<Action>
|
||||
// grant like every other IAM action. Off by default.
|
||||
selfServiceRequiresGrant bool
|
||||
|
||||
// Serializes resyncs of the policy set into the advanced IAM manager so that
|
||||
// concurrent policy updates can't apply stale views out of order. See
|
||||
// resyncIAMManagerPolicies.
|
||||
@@ -342,7 +336,6 @@ func NewIdentityAccessManagementWithStore(option *S3ApiServerOption, filerClient
|
||||
hashCounters: make(map[string]*int32),
|
||||
filerClient: filerClient,
|
||||
}
|
||||
iam.selfServiceRequiresGrant = option.IamSelfServiceRequiresGrant
|
||||
|
||||
// Always initialize credential manager with fallback to defaults
|
||||
credentialManager, err := credential.NewCredentialManagerWithDefaults(credential.CredentialStoreTypeName(explicitStore))
|
||||
@@ -1687,7 +1680,6 @@ func (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) htt
|
||||
// succeeds but authZ denies, so the denied request still audits its
|
||||
// requester; a failed authN resolves no identity at all.
|
||||
identity, errCode, _ := iam.authRequestWithAuthType(r, action)
|
||||
errCode = refineDenialForBucketName(r, identity, errCode)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.V(3).Infof("auth error: %v", errCode)
|
||||
}
|
||||
@@ -1727,7 +1719,6 @@ func (iam *IdentityAccessManagement) AuthPostPolicy(f http.HandlerFunc, action A
|
||||
}
|
||||
}
|
||||
|
||||
errCode = refineDenialForBucketName(r, identity, errCode)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.V(3).Infof("auth error: %v", errCode)
|
||||
}
|
||||
@@ -1736,39 +1727,6 @@ func (iam *IdentityAccessManagement) AuthPostPolicy(f http.HandlerFunc, action A
|
||||
}
|
||||
}
|
||||
|
||||
// refineDenialForBucketName answers 400 InvalidBucketName, as AWS S3 does,
|
||||
// when an authenticated caller is denied on a bucket whose name breaks the S3
|
||||
// naming rules. The rules are public and the answer depends on the name alone,
|
||||
// so it tells the caller nothing about which buckets exist. Authentication
|
||||
// failures (no identity resolved) and every other answer are left unchanged.
|
||||
func refineDenialForBucketName(r *http.Request, identity *Identity, errCode s3err.ErrorCode) s3err.ErrorCode {
|
||||
if errCode != s3err.ErrAccessDenied || identity == nil {
|
||||
return errCode
|
||||
}
|
||||
bucket, _ := s3_constants.GetBucketAndObject(r)
|
||||
if bucket == "" {
|
||||
return errCode
|
||||
}
|
||||
if !isASCIIBucketName(bucket) || s3bucket.VerifyS3BucketName(bucket) != nil {
|
||||
return s3err.ErrInvalidBucketName
|
||||
}
|
||||
return errCode
|
||||
}
|
||||
|
||||
// isASCIIBucketName reports whether name uses only the characters S3 allows
|
||||
// in a bucket name. VerifyS3BucketName checks with unicode.IsLower and
|
||||
// unicode.IsNumber, which also accept letters such as 'ü' and digits such as
|
||||
// '²' that S3 refuses.
|
||||
func isASCIIBucketName(name string) bool {
|
||||
for i := 0; i < len(name); i++ {
|
||||
c := name[i]
|
||||
if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '.' || c == '-') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// recordIdentityInContext stores the authenticated identity, its name and its
|
||||
// principal ARN in the request context. An STS session's name is only an opaque
|
||||
// session subject, so the ARN is what carries the assumed role and session name
|
||||
@@ -3067,21 +3025,11 @@ func (iam *IdentityAccessManagement) bucketsNamedByAttachedPolicies(r *http.Requ
|
||||
// its query describe. versionId, when set, and the STS session token ride along
|
||||
// for policy conditions. Returns ErrNone when auth is disabled (checked by the
|
||||
// callers) or the identity is an admin.
|
||||
// authQueryParams are the query keys carrying a request's authentication
|
||||
// material (SigV2 and SigV4 presign parameters). None steer ResolveS3Action,
|
||||
// so they can ride along on a synthesized request.
|
||||
var authQueryParams = []string{
|
||||
"AWSAccessKeyId", "Signature", "Expires",
|
||||
"X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date", "X-Amz-Expires",
|
||||
"X-Amz-Signature", "X-Amz-SignedHeaders", "X-Amz-Security-Token",
|
||||
}
|
||||
|
||||
// objectKeyPolicyRequest synthesizes a <method> /<bucket>/<objectKey> request
|
||||
// for policy evaluation against a key the real URL does not name. The query is
|
||||
// built from scratch so a param on the real request (delete, uploadId,
|
||||
// partNumber, ...) cannot steer ResolveS3Action off the intended action; the
|
||||
// versionId and the auth-material params ride along so auth-derived policy
|
||||
// conditions (s3:authType) evaluate as they did on the real request.
|
||||
// STS token and versionId ride along for policy conditions.
|
||||
func objectKeyPolicyRequest(r *http.Request, method, bucket, objectKey, versionId string) *http.Request {
|
||||
keyReq := new(http.Request)
|
||||
*keyReq = *r
|
||||
@@ -3094,9 +3042,9 @@ func objectKeyPolicyRequest(r *http.Request, method, bucket, objectKey, versionI
|
||||
if versionId != "" {
|
||||
keyQuery.Set("versionId", versionId)
|
||||
}
|
||||
for _, key := range authQueryParams {
|
||||
if vals, ok := r.URL.Query()[key]; ok {
|
||||
keyQuery[key] = vals
|
||||
if strings.Contains(r.URL.RawQuery, "X-Amz-Security-Token") {
|
||||
if token := r.URL.Query().Get("X-Amz-Security-Token"); token != "" {
|
||||
keyQuery.Set("X-Amz-Security-Token", token)
|
||||
}
|
||||
}
|
||||
if len(keyQuery) > 0 {
|
||||
|
||||
@@ -1,250 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
invalidNameTestAccessKey = "INVALIDNAMEKEY000001"
|
||||
invalidNameTestSecretKey = "invalid-name-secret-for-tests-only"
|
||||
invalidNameTestBucket = "readable-bucket"
|
||||
)
|
||||
|
||||
// newInvalidNameIAM has one identity that may read invalidNameTestBucket only
|
||||
// and a configured anonymous identity with no actions.
|
||||
func newInvalidNameIAM(t *testing.T) *IdentityAccessManagement {
|
||||
t.Helper()
|
||||
iam := &IdentityAccessManagement{hashes: make(map[string]*sync.Pool), hashCounters: make(map[string]*int32)}
|
||||
require.NoError(t, iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{Name: "reader", Actions: []string{"Read:" + invalidNameTestBucket},
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: invalidNameTestAccessKey, SecretKey: invalidNameTestSecretKey}}},
|
||||
{Name: s3_constants.AccountAnonymousId},
|
||||
},
|
||||
}))
|
||||
require.True(t, iam.isEnabled())
|
||||
return iam
|
||||
}
|
||||
|
||||
func invalidNameRequest(t *testing.T, bucket string, sign bool) *http.Request {
|
||||
t.Helper()
|
||||
req := mustNewRequest(http.MethodGet, fmt.Sprintf("http://127.0.0.1:8333/%s/key", bucket), 0, nil, t)
|
||||
if sign {
|
||||
require.NoError(t, signRequestV4(req, invalidNameTestAccessKey, invalidNameTestSecretKey))
|
||||
}
|
||||
return mux.SetURLVars(req, map[string]string{"bucket": bucket, "object": "key"})
|
||||
}
|
||||
|
||||
func serveAuth(iam *IdentityAccessManagement, r *http.Request) (int, bool) {
|
||||
ran := false
|
||||
rec := httptest.NewRecorder()
|
||||
iam.Auth(func(w http.ResponseWriter, r *http.Request) { ran = true; w.WriteHeader(http.StatusOK) }, s3_constants.ACTION_READ).ServeHTTP(rec, r)
|
||||
return rec.Code, ran
|
||||
}
|
||||
|
||||
// A denied request on a malformed bucket name answers 400 InvalidBucketName,
|
||||
// as AWS S3 does; a denied request on a well-formed name stays 403.
|
||||
func TestAuthDeniedInvalidBucketName(t *testing.T) {
|
||||
iam := newInvalidNameIAM(t)
|
||||
|
||||
code, ran := serveAuth(iam, invalidNameRequest(t, invalidNameTestBucket, true))
|
||||
assert.True(t, ran, "the identity's own bucket is allowed")
|
||||
assert.Equal(t, http.StatusOK, code)
|
||||
|
||||
code, ran = serveAuth(iam, invalidNameRequest(t, "other-bucket", true))
|
||||
assert.False(t, ran)
|
||||
assert.Equal(t, http.StatusForbidden, code, "a well-formed name the caller may not read stays AccessDenied")
|
||||
|
||||
for _, bucket := range []string{"Bad_Bucket", "ab", "bucket..name", "bücket"} {
|
||||
for _, sign := range []bool{true, false} {
|
||||
code, ran = serveAuth(iam, invalidNameRequest(t, bucket, sign))
|
||||
assert.False(t, ran, bucket)
|
||||
assert.Equal(t, http.StatusBadRequest, code, "bucket %q signed=%v", bucket, sign)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefineDenialForBucketName(t *testing.T) {
|
||||
reader := &Identity{Name: "reader"}
|
||||
req := func(bucket string) *http.Request {
|
||||
return mux.SetURLVars(httptest.NewRequest(http.MethodGet, "/", nil), map[string]string{"bucket": bucket})
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
bucket string
|
||||
identity *Identity
|
||||
in, want s3err.ErrorCode
|
||||
}{
|
||||
{"space in the name", "bucket name", reader, s3err.ErrAccessDenied, s3err.ErrInvalidBucketName},
|
||||
{"non-ASCII letter", "bücket", reader, s3err.ErrAccessDenied, s3err.ErrInvalidBucketName},
|
||||
{"superscript digit", "b²cket", reader, s3err.ErrAccessDenied, s3err.ErrInvalidBucketName},
|
||||
{"too short", "ab", reader, s3err.ErrAccessDenied, s3err.ErrInvalidBucketName},
|
||||
{"well-formed name", "other-bucket", reader, s3err.ErrAccessDenied, s3err.ErrAccessDenied},
|
||||
{"no bucket in the request", "", reader, s3err.ErrAccessDenied, s3err.ErrAccessDenied},
|
||||
{"allowed", "Bad_Bucket", reader, s3err.ErrNone, s3err.ErrNone},
|
||||
{"authentication failed", "Bad_Bucket", nil, s3err.ErrAccessDenied, s3err.ErrAccessDenied},
|
||||
{"bad signature", "Bad_Bucket", nil, s3err.ErrSignatureDoesNotMatch, s3err.ErrSignatureDoesNotMatch},
|
||||
}
|
||||
for _, c := range cases {
|
||||
assert.Equal(t, c.want, refineDenialForBucketName(req(c.bucket), c.identity, c.in), c.name)
|
||||
}
|
||||
}
|
||||
|
||||
// signedPostForm builds a multipart POST Object request for bucket, its policy
|
||||
// signed with secret under postAuthzAccessKey.
|
||||
func signedPostForm(t *testing.T, bucket, key, secret string) *http.Request {
|
||||
t.Helper()
|
||||
now := time.Now().UTC()
|
||||
amzDate := now.Format(iso8601Format)
|
||||
day := now.Format(yyyymmdd)
|
||||
credential := fmt.Sprintf("%s/%s/%s/%s/aws4_request", postAuthzAccessKey, day, postAuthzRegion, postAuthzService)
|
||||
policyJSON := fmt.Sprintf(`{"expiration":"%s","conditions":[["eq","$bucket","%s"],["eq","$key","%s"],`+
|
||||
`["eq","$x-amz-credential","%s"],["eq","$x-amz-algorithm","AWS4-HMAC-SHA256"],["eq","$x-amz-date","%s"]]}`,
|
||||
now.Add(time.Hour).Format("2006-01-02T15:04:05.000Z"), bucket, key, credential, amzDate)
|
||||
encodedPolicy := base64.StdEncoding.EncodeToString([]byte(policyJSON))
|
||||
signature := getSignature(getSigningKey(secret, day, postAuthzRegion, postAuthzService), encodedPolicy)
|
||||
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
for _, field := range [][2]string{{"bucket", bucket}, {"key", key}, {"x-amz-credential", credential},
|
||||
{"x-amz-algorithm", "AWS4-HMAC-SHA256"}, {"x-amz-date", amzDate}, {"policy", encodedPolicy}, {"x-amz-signature", signature}} {
|
||||
require.NoError(t, writer.WriteField(field[0], field[1]))
|
||||
}
|
||||
filePart, err := writer.CreateFormFile("file", "payload.txt")
|
||||
require.NoError(t, err)
|
||||
_, err = filePart.Write([]byte("payload"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, writer.Close())
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/"+bucket, &buf)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
return mux.SetURLVars(req, map[string]string{"bucket": bucket})
|
||||
}
|
||||
|
||||
// A browser POST upload authenticates in the handler, after AuthPostPolicy has
|
||||
// delegated it, so its denials are refined there: a verified form denied on a
|
||||
// malformed bucket name answers 400, a bad signature or a well-formed name 403.
|
||||
func TestPostPolicyDeniedInvalidBucketName(t *testing.T) {
|
||||
s3a := newPostAuthzServer(t)
|
||||
for _, bucket := range []string{"Bad_Bucket", "other-bucket"} {
|
||||
s3a.bucketRegistry.setMetadataCache(&BucketMetaData{Name: bucket})
|
||||
}
|
||||
// A second identity may write Bad_Bucket, except under denied/.
|
||||
require.NoError(t, s3a.iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{Name: "tester", Actions: []string{"Write:" + postAuthzBucket},
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: postAuthzAccessKey, SecretKey: postAuthzSecretKey}}},
|
||||
},
|
||||
}))
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("Bad_Bucket", `{"Version":"2012-10-17","Statement":[`+
|
||||
`{"Effect":"Deny","Principal":"*","Action":["s3:PutObject"],"Resource":["arn:aws:s3:::Bad_Bucket/denied/*"]}]}`))
|
||||
|
||||
serve := func(r *http.Request) *httptest.ResponseRecorder {
|
||||
rec := httptest.NewRecorder()
|
||||
s3a.iam.AuthPostPolicy(s3a.PostPolicyBucketHandler, s3_constants.ACTION_WRITE).ServeHTTP(rec, r)
|
||||
return rec
|
||||
}
|
||||
|
||||
rec := serve(signedPostForm(t, "Bad_Bucket", "k", postAuthzSecretKey))
|
||||
assert.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
assert.Contains(t, rec.Body.String(), "InvalidBucketName")
|
||||
|
||||
rec = serve(signedPostForm(t, "Bad_Bucket", "k", "not-the-secret"))
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
|
||||
assert.Contains(t, rec.Body.String(), "SignatureDoesNotMatch", "a form that fails verification is not refined")
|
||||
|
||||
rec = serve(signedPostForm(t, "other-bucket", "k", postAuthzSecretKey))
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
|
||||
assert.Contains(t, rec.Body.String(), "AccessDenied")
|
||||
|
||||
// The per-key authorization after the coarse Write check is refined too.
|
||||
require.NoError(t, s3a.iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{Name: "tester", Actions: []string{"Write:Bad_Bucket"},
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: postAuthzAccessKey, SecretKey: postAuthzSecretKey}}},
|
||||
},
|
||||
}))
|
||||
rec = serve(signedPostForm(t, "Bad_Bucket", "denied/k", postAuthzSecretKey))
|
||||
assert.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
assert.Contains(t, rec.Body.String(), "InvalidBucketName")
|
||||
}
|
||||
|
||||
// Unsigned GET/HEAD object reads are authorized inside the object handlers, not
|
||||
// by Auth; their denial on a malformed bucket name answers 400 as well.
|
||||
func TestAnonymousReadDeniedInvalidBucketName(t *testing.T) {
|
||||
read := func(s3a *S3ApiServer, method, bucket string) int {
|
||||
r := httptest.NewRequest(method, "/"+bucket+"/key", nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": bucket, "object": "key"})
|
||||
handler := s3a.GetObjectHandler
|
||||
if method == http.MethodHead {
|
||||
handler = s3a.HeadObjectHandler
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
s3a.AuthWithPublicRead(handler, s3_constants.ACTION_READ)(rr, r)
|
||||
return rr.Code
|
||||
}
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
s3a, _ := newAnonymousReadTestServer(t)
|
||||
s3a.iam.identityAnonymous = &Identity{Name: s3_constants.AccountAnonymousId}
|
||||
assert.Equal(t, http.StatusBadRequest, read(s3a, method, "Bad_Bucket"), method)
|
||||
assert.Equal(t, http.StatusForbidden, read(s3a, method, "other-bucket"), "%s: a well-formed missing bucket stays masked", method)
|
||||
|
||||
// No anonymous identity configured: no identity resolves, as in Auth.
|
||||
s3a, _ = newAnonymousReadTestServer(t)
|
||||
assert.Equal(t, http.StatusForbidden, read(s3a, method, "Bad_Bucket"), method)
|
||||
}
|
||||
}
|
||||
|
||||
// An existing private key and a missing key in the same malformed-name bucket
|
||||
// must answer alike, or the status code tells an anonymous caller which keys
|
||||
// exist.
|
||||
func TestAnonymousReadDeniedInvalidBucketNameExistingKey(t *testing.T) {
|
||||
const bucket = "bücket"
|
||||
read := func(s3a *S3ApiServer, method, object string) int {
|
||||
r := httptest.NewRequest(method, "/"+bucket+"/"+object, nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": bucket, "object": object})
|
||||
handler := s3a.GetObjectHandler
|
||||
if method == http.MethodHead {
|
||||
handler = s3a.HeadObjectHandler
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
s3a.AuthWithPublicRead(handler, s3_constants.ACTION_READ)(rr, r)
|
||||
return rr.Code
|
||||
}
|
||||
setup := func(anonymous bool) *S3ApiServer {
|
||||
s3a, f := newAnonymousReadTestServer(t)
|
||||
if anonymous {
|
||||
s3a.iam.identityAnonymous = &Identity{Name: s3_constants.AccountAnonymousId}
|
||||
}
|
||||
s3a.bucketConfigCache.Set(bucket, &BucketConfig{Name: bucket, Ownership: s3_constants.OwnershipObjectWriter})
|
||||
f.entries["/buckets/"+bucket+"/private"] = anonymousReadEntry([]byte(`[]`))
|
||||
f.entries["/buckets/"+bucket+"/public"] = anonymousReadEntry(anonymousReadGrant("READ"))
|
||||
return s3a
|
||||
}
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
s3a := setup(true)
|
||||
assert.Equal(t, http.StatusOK, read(s3a, method, "public"), "%s: a public key is still served", method)
|
||||
assert.Equal(t, http.StatusBadRequest, read(s3a, method, "missing"), method)
|
||||
assert.Equal(t, http.StatusBadRequest, read(s3a, method, "private"), "%s: an existing private key answers like a missing one", method)
|
||||
|
||||
// No anonymous identity configured: both stay 403, as in Auth.
|
||||
s3a = setup(false)
|
||||
assert.Equal(t, http.StatusForbidden, read(s3a, method, "missing"), method)
|
||||
assert.Equal(t, http.StatusForbidden, read(s3a, method, "private"), method)
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"crypto/subtle"
|
||||
@@ -69,7 +68,7 @@ func (iam *IdentityAccessManagement) isReqAuthenticatedV2(r *http.Request) (*Ide
|
||||
return iam.doesPresignV2SignatureMatch(r)
|
||||
}
|
||||
|
||||
func (iam *IdentityAccessManagement) doesPolicySignatureV2Match(ctx context.Context, formValues http.Header) (*Identity, s3err.ErrorCode) {
|
||||
func (iam *IdentityAccessManagement) doesPolicySignatureV2Match(formValues http.Header) (*Identity, s3err.ErrorCode) {
|
||||
|
||||
accessKey := formValues.Get("AWSAccessKeyId")
|
||||
if accessKey == "" {
|
||||
@@ -96,6 +95,11 @@ func (iam *IdentityAccessManagement) doesPolicySignatureV2Match(ctx context.Cont
|
||||
return nil, s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
bucket := formValues.Get("bucket")
|
||||
if !identity.CanDo(s3_constants.ACTION_WRITE, bucket, "") {
|
||||
return nil, s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
policy := formValues.Get("Policy")
|
||||
if policy == "" {
|
||||
return nil, s3err.ErrMissingFields
|
||||
@@ -109,7 +113,6 @@ func (iam *IdentityAccessManagement) doesPolicySignatureV2Match(ctx context.Cont
|
||||
if !compareSignatureV2(signature, calculateSignatureV2(policy, cred.SecretKey)) {
|
||||
return nil, s3err.ErrSignatureDoesNotMatch
|
||||
}
|
||||
s3_constants.RecordAccessKeyId(ctx, cred.AccessKey)
|
||||
return identity, s3err.ErrNone
|
||||
}
|
||||
|
||||
@@ -167,7 +170,6 @@ func (iam *IdentityAccessManagement) doesSignV2Match(r *http.Request) (*Identity
|
||||
if !compareSignatureV2(v2Signature, expectedV2Signature) {
|
||||
return nil, s3err.ErrSignatureDoesNotMatch
|
||||
}
|
||||
s3_constants.RecordAccessKeyId(r.Context(), cred.AccessKey)
|
||||
return identity, s3err.ErrNone
|
||||
}
|
||||
|
||||
@@ -226,7 +228,6 @@ func (iam *IdentityAccessManagement) doesPresignV2SignatureMatch(r *http.Request
|
||||
if !compareSignatureV2(signature, expectedSignature) {
|
||||
return nil, s3err.ErrSignatureDoesNotMatch
|
||||
}
|
||||
s3_constants.RecordAccessKeyId(r.Context(), cred.AccessKey)
|
||||
return identity, s3err.ErrNone
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
@@ -408,10 +407,6 @@ func (iam *IdentityAccessManagement) verifyV4Signature(r *http.Request, shouldCh
|
||||
}
|
||||
|
||||
if matchedHost != "" {
|
||||
// The key of the credential that verified: the audit log and the
|
||||
// catalog's vended sessions name it (never a key re-read from the request).
|
||||
// Recorded before the retarget check so that refusal names it too.
|
||||
s3_constants.RecordAccessKeyId(r.Context(), cred.AccessKey)
|
||||
if signedBucket, ok := bucketFromVirtualHost(matchedHost, iam.domain); ok {
|
||||
if routedBucket, _ := s3_constants.GetBucketAndObject(r); routedBucket != "" && routedBucket != signedBucket {
|
||||
glog.V(2).Infof("reject %s %s: signed host %q implies bucket %q but routed to %q",
|
||||
@@ -835,7 +830,7 @@ func parseSignedHeaderList(signedHeadersValue string) ([]string, s3err.ErrorCode
|
||||
return signedHeaders, s3err.ErrNone
|
||||
}
|
||||
|
||||
func (iam *IdentityAccessManagement) doesPolicySignatureV4Match(ctx context.Context, formValues http.Header) (*Identity, s3err.ErrorCode) {
|
||||
func (iam *IdentityAccessManagement) doesPolicySignatureV4Match(formValues http.Header) (*Identity, s3err.ErrorCode) {
|
||||
|
||||
// Parse credential tag.
|
||||
credHeader, err := parseCredentialHeader("Credential=" + formValues.Get("X-Amz-Credential"))
|
||||
@@ -863,6 +858,11 @@ func (iam *IdentityAccessManagement) doesPolicySignatureV4Match(ctx context.Cont
|
||||
return nil, s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
bucket := formValues.Get("bucket")
|
||||
if !identity.CanDo(s3_constants.ACTION_WRITE, bucket, "") {
|
||||
return nil, s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
// Get signing key.
|
||||
signingKey := getSigningKey(cred.SecretKey, credHeader.scope.date.Format(yyyymmdd), credHeader.scope.region, credHeader.scope.service)
|
||||
|
||||
@@ -873,7 +873,6 @@ func (iam *IdentityAccessManagement) doesPolicySignatureV4Match(ctx context.Cont
|
||||
if !compareSignatureV4(newSignature, formValues.Get("X-Amz-Signature")) {
|
||||
return nil, s3err.ErrSignatureDoesNotMatch
|
||||
}
|
||||
s3_constants.RecordAccessKeyId(ctx, cred.AccessKey)
|
||||
return identity, s3err.ErrNone
|
||||
}
|
||||
|
||||
|
||||
@@ -2,12 +2,8 @@ package s3api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -87,117 +83,6 @@ func (s3a *S3ApiServer) validateTableBucketObjectPath(bucket, object string) err
|
||||
return nil
|
||||
}
|
||||
|
||||
// volumeVerifyKey matches the object Snowflake writes, reads, lists and
|
||||
// deletes at the base of an S3-compatible external volume before it creates
|
||||
// or writes Iceberg tables there (SYSTEM$VERIFY_EXTERNAL_VOLUME, also run
|
||||
// implicitly): <base>/verify_<epoch milliseconds>_<number>, a 21-byte body.
|
||||
// A table bucket refuses every key outside the Iceberg layout, so without
|
||||
// this exception Snowflake cannot use a table bucket as an external volume.
|
||||
//
|
||||
// The exception is narrow so that it cannot be used to store data:
|
||||
// - only at the bucket root: nothing can be encoded in a prefix, written
|
||||
// into a hidden tree or take a namespace or table name;
|
||||
// - one shape: 13 digits of epoch milliseconds, then 1-10 digits;
|
||||
// - never a directory: a namespace may carry a name of that shape, and the
|
||||
// key then names its directory (volumeVerifyKeyIsDirectory);
|
||||
// - a PUT must be dated within volumeVerifyWindow of the server's clock,
|
||||
// declare a Content-Length of at most volumeVerifyMaxBytes (no chunked or
|
||||
// undeclared body), and carry no user metadata, tagging, stored content
|
||||
// headers or extraction request (volumeVerifyPutAllowed). Reads and
|
||||
// deletes take a key of any date, so an object a check left behind can
|
||||
// still be removed.
|
||||
//
|
||||
// Only the calls the check makes (PUT, GET, HEAD, DELETE, DeleteObjects)
|
||||
// accept the key; multipart, copy, rename, ACL, tagging and POST policy keep
|
||||
// the plain layout rule.
|
||||
var volumeVerifyKey = regexp.MustCompile(`^verify_([0-9]{13})_[0-9]{1,10}$`)
|
||||
|
||||
const (
|
||||
volumeVerifyMaxBytes = 1024
|
||||
volumeVerifyWindow = time.Hour
|
||||
)
|
||||
|
||||
// volumeVerifyNow is the clock a PUT's key is checked against.
|
||||
var volumeVerifyNow = time.Now
|
||||
|
||||
// volumeVerifyKeyTime is the time a verification key is dated, and whether
|
||||
// the object has the key's shape.
|
||||
func volumeVerifyKeyTime(object string) (time.Time, bool) {
|
||||
m := volumeVerifyKey.FindStringSubmatch(strings.TrimPrefix(object, "/"))
|
||||
if m == nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
ms, err := strconv.ParseInt(m[1], 10, 64)
|
||||
if err != nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return time.UnixMilli(ms), true
|
||||
}
|
||||
|
||||
func isVolumeVerifyKey(object string) bool {
|
||||
_, ok := volumeVerifyKeyTime(object)
|
||||
return ok
|
||||
}
|
||||
|
||||
// volumeVerifyLookup reads the entry a verification key names.
|
||||
var volumeVerifyLookup = func(s3a *S3ApiServer, dir, name string) (*filer_pb.Entry, error) {
|
||||
return s3a.getEntry(dir, name)
|
||||
}
|
||||
|
||||
// volumeVerifyKeyIsDirectory reports whether the key names a directory (a
|
||||
// namespace), or whether that cannot be known.
|
||||
func (s3a *S3ApiServer) volumeVerifyKeyIsDirectory(bucket, object string) bool {
|
||||
entry, err := volumeVerifyLookup(s3a, s3a.bucketDir(bucket), strings.TrimPrefix(object, "/"))
|
||||
if err != nil {
|
||||
return !errors.Is(err, filer_pb.ErrNotFound)
|
||||
}
|
||||
return entry != nil && entry.IsDirectory
|
||||
}
|
||||
|
||||
// validateTableBucketObjectPathOrVerify is validateTableBucketObjectPath that
|
||||
// also accepts the external-volume verification key, and reports it so the
|
||||
// PUT handler can apply its limits.
|
||||
func (s3a *S3ApiServer) validateTableBucketObjectPathOrVerify(bucket, object string) (isVerify bool, err error) {
|
||||
if !s3a.isTableBucket(bucket) {
|
||||
return false, nil
|
||||
}
|
||||
if isVolumeVerifyKey(object) && !s3a.volumeVerifyKeyIsDirectory(bucket, object) {
|
||||
return true, nil
|
||||
}
|
||||
return false, s3a.validateTableBucketObjectPath(bucket, object)
|
||||
}
|
||||
|
||||
// volumeVerifyPutAllowed reports whether a PUT to the verification key is
|
||||
// dated now, declares a small body and stores nothing beside it.
|
||||
func volumeVerifyPutAllowed(r *http.Request, object string) bool {
|
||||
at, ok := volumeVerifyKeyTime(object)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if d := volumeVerifyNow().Sub(at); d > volumeVerifyWindow || d < -volumeVerifyWindow {
|
||||
return false
|
||||
}
|
||||
if r.ContentLength < 0 || r.ContentLength > volumeVerifyMaxBytes || len(r.TransferEncoding) > 0 {
|
||||
return false
|
||||
}
|
||||
if isExtractZip(r) {
|
||||
return false
|
||||
}
|
||||
for name, values := range r.Header {
|
||||
n := strings.ToLower(name)
|
||||
if strings.HasPrefix(n, "x-amz-meta-") || n == "x-amz-tagging" || n == "content-disposition" ||
|
||||
n == "response-content-disposition" || n == "content-language" ||
|
||||
n == "cache-control" || n == "expires" || n == "x-amz-website-redirect-location" {
|
||||
return false
|
||||
}
|
||||
// aws-chunked only frames the body; any other coding is stored.
|
||||
if n == "content-encoding" && storedContentEncoding(values) != "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) bucketPrefix(bucket string) string {
|
||||
return s3a.bucketDir(bucket) + "/"
|
||||
}
|
||||
|
||||
@@ -252,59 +252,3 @@ func (s *Server) finalizeCreateOnCommit(ctx context.Context, input createOnCommi
|
||||
Metadata: newMetadata,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// authorizeCommit asks the S3 Tables layer, before anything is written, whether
|
||||
// the caller may update the table. Both commit paths stage the new metadata
|
||||
// file in the table's directory before UpdateTable authorizes the pointer
|
||||
// flip, so without this gate a caller who may only read the table could still
|
||||
// make the server write and delete files under it. UpdateTable decides again
|
||||
// when the pointer flips.
|
||||
func (s *Server) authorizeCommit(ctx context.Context, bucketARN string, namespace []string, tableName, identityName string) *icebergRequestError {
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return s.tablesManager.AuthorizeUpdateTable(ctx, s3tables.NewManagerClient(client), &s3tables.UpdateTableRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
Name: tableName,
|
||||
}, identityName)
|
||||
})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var tableErr *s3tables.S3TablesError
|
||||
if errors.As(err, &tableErr) {
|
||||
switch tableErr.Type {
|
||||
case s3tables.ErrCodeAccessDenied:
|
||||
return &icebergRequestError{http.StatusForbidden, "ForbiddenException", fmt.Sprintf("Not authorized to commit to table %s", tableName)}
|
||||
case s3tables.ErrCodeNoSuchTable, s3tables.ErrCodeNoSuchNamespace:
|
||||
return &icebergRequestError{http.StatusNotFound, "NoSuchTableException", fmt.Sprintf("Table does not exist: %s", tableName)}
|
||||
}
|
||||
}
|
||||
glog.V(1).Infof("Iceberg: commit authorization for %s failed: %v", tableName, err)
|
||||
return &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Failed to authorize commit: " + err.Error()}
|
||||
}
|
||||
|
||||
// authorizeViewCommit is authorizeCommit for a view, whose update path stages
|
||||
// its metadata file before UpdateView authorizes the pointer flip.
|
||||
func (s *Server) authorizeViewCommit(ctx context.Context, bucketARN string, namespace []string, viewName, identityName string) *icebergRequestError {
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return s.tablesManager.AuthorizeUpdateView(ctx, s3tables.NewManagerClient(client), &s3tables.UpdateViewRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
Name: viewName,
|
||||
}, identityName)
|
||||
})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var tableErr *s3tables.S3TablesError
|
||||
if errors.As(err, &tableErr) {
|
||||
switch tableErr.Type {
|
||||
case s3tables.ErrCodeAccessDenied:
|
||||
return &icebergRequestError{http.StatusForbidden, "ForbiddenException", fmt.Sprintf("Not authorized to commit to view %s", viewName)}
|
||||
case s3tables.ErrCodeNoSuchView, s3tables.ErrCodeNoSuchNamespace:
|
||||
return &icebergRequestError{http.StatusNotFound, "NoSuchViewException", fmt.Sprintf("View does not exist: %s", viewName)}
|
||||
}
|
||||
}
|
||||
glog.V(1).Infof("Iceberg: view commit authorization for %s failed: %v", viewName, err)
|
||||
return &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Failed to authorize commit: " + err.Error()}
|
||||
}
|
||||
@@ -242,10 +242,6 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) {
|
||||
writeManagerError(w, err)
|
||||
return
|
||||
}
|
||||
if reqErr := s.authorizeCommit(r.Context(), bucketARN, namespace, tableName, identityName); reqErr != nil {
|
||||
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
|
||||
return
|
||||
}
|
||||
|
||||
location := tableLocationFromMetadataLocation(getResp.MetadataLocation)
|
||||
if location == "" {
|
||||
@@ -401,7 +397,7 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) {
|
||||
if cleanupErr := s.deleteMetadataFile(r.Context(), metadataBucket, metadataPath, metadataFileName); cleanupErr != nil {
|
||||
glog.V(1).Infof("Iceberg: failed to cleanup metadata file %s after update failure: %v", newMetadataLocation, cleanupErr)
|
||||
}
|
||||
logManagerError("CommitTable UpdateTable", err)
|
||||
glog.Errorf("Iceberg: CommitTable UpdateTable error: %v", err)
|
||||
writeManagerError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -140,7 +140,7 @@ func (s *Server) handleCreateNamespace(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusConflict, "AlreadyExistsException", err.Error())
|
||||
return
|
||||
}
|
||||
logManagerError("CreateNamespace", err)
|
||||
glog.Errorf("Iceberg: CreateNamespace error: %v", err)
|
||||
writeManagerError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -324,28 +324,20 @@ func mintIcebergToken(identityName, accessKey, secret string, ttlSeconds int) (s
|
||||
// authenticateBearer validates a Bearer token from the Authorization header.
|
||||
// Returns the identity name, identity object, and whether auth succeeded.
|
||||
func (s *Server) authenticateBearer(r *http.Request) (string, interface{}, bool) {
|
||||
identityName, identity, _, ok := s.authenticateBearerKey(r)
|
||||
return identityName, identity, ok
|
||||
}
|
||||
|
||||
// authenticateBearerKey is authenticateBearer that also returns the access key
|
||||
// the token was minted from (its verified access_key claim), so the catalog
|
||||
// can tell apart the holders of several keys on one identity.
|
||||
func (s *Server) authenticateBearerKey(r *http.Request) (string, interface{}, string, bool) {
|
||||
auth := r.Header.Get("Authorization")
|
||||
if auth == "" {
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
if !strings.HasPrefix(strings.ToLower(auth), "bearer ") {
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
tokenString := strings.TrimSpace(auth[7:])
|
||||
if tokenString == "" {
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
if s.credentialValidator == nil {
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
// Parse the token without verification first to get the access key,
|
||||
@@ -355,18 +347,18 @@ func (s *Server) authenticateBearerKey(r *http.Request) (string, interface{}, st
|
||||
_, _, err := parser.ParseUnverified(tokenString, unverified)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("Iceberg OAuth: failed to parse token: %v", err)
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
if unverified.AccessKey == "" {
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
// Look up the credential by access key to get the signing key for verification
|
||||
identityName, identity, secretKey, err := s.credentialValidator.GetCredentialByAccessKey(unverified.AccessKey)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("Iceberg OAuth: failed to get credential for access key: %v", err)
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
signingKey := deriveSigningKey(unverified.AccessKey, secretKey)
|
||||
@@ -379,12 +371,10 @@ func (s *Server) authenticateBearerKey(r *http.Request) (string, interface{}, st
|
||||
})
|
||||
if err != nil || !verified.Valid {
|
||||
glog.V(2).Infof("Iceberg OAuth: token verification failed: %v", err)
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
// The token's signing key is derived from this access key, so a verified
|
||||
// token was minted from it.
|
||||
return identityName, identity, unverified.AccessKey, true
|
||||
return identityName, identity, true
|
||||
}
|
||||
|
||||
// deriveSigningKey derives a signing key from the access key and secret using HMAC-SHA256.
|
||||
|
||||
@@ -109,7 +109,7 @@ func (s *Server) handleCommitTransaction(w http.ResponseWriter, r *http.Request)
|
||||
writeError(w, http.StatusConflict, "CommitFailedException", "Version token mismatch")
|
||||
return
|
||||
}
|
||||
logManagerError("CommitTransaction UpdateTable", err)
|
||||
glog.Errorf("Iceberg: CommitTransaction UpdateTable error: %v", err)
|
||||
writeManagerError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -140,9 +140,6 @@ func (s *Server) prepareTableCommit(ctx context.Context, bucketName, bucketARN,
|
||||
glog.V(1).Infof("Iceberg: CommitTransaction GetTable error: %v", err)
|
||||
return nil, &icebergRequestError{http.StatusInternalServerError, "InternalServerError", err.Error()}
|
||||
}
|
||||
if reqErr := s.authorizeCommit(ctx, bucketARN, namespace, tableName, identityName); reqErr != nil {
|
||||
return nil, reqErr
|
||||
}
|
||||
|
||||
location := tableLocationFromMetadataLocation(getResp.MetadataLocation)
|
||||
if location == "" {
|
||||
|
||||
@@ -48,10 +48,6 @@ func (s *Server) handleUpdateView(w http.ResponseWriter, r *http.Request) {
|
||||
writeManagerError(w, err)
|
||||
return
|
||||
}
|
||||
if reqErr := s.authorizeViewCommit(r.Context(), bucketARN, namespace, viewName, identityName); reqErr != nil {
|
||||
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
|
||||
return
|
||||
}
|
||||
if getResp.Metadata == nil || len(getResp.Metadata.FullMetadata) == 0 {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "view has no metadata")
|
||||
return
|
||||
|
||||
@@ -1,237 +0,0 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/apache/iceberg-go"
|
||||
"github.com/apache/iceberg-go/table"
|
||||
"github.com/apache/iceberg-go/view"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// writeLogFiler records every file the handlers create, including files they
|
||||
// delete again before answering, which the final entry map cannot show.
|
||||
type writeLogFiler struct {
|
||||
*memFiler
|
||||
created []string
|
||||
}
|
||||
|
||||
func (f *writeLogFiler) WithFilerClient(_ bool, fn func(client filer_pb.SeaweedFilerClient) error) error {
|
||||
return fn(f)
|
||||
}
|
||||
|
||||
func (f *writeLogFiler) CreateEntry(ctx context.Context, in *filer_pb.CreateEntryRequest, opts ...grpc.CallOption) (*filer_pb.CreateEntryResponse, error) {
|
||||
if !in.Entry.IsDirectory {
|
||||
f.created = append(f.created, path.Join(in.Directory, in.Entry.Name))
|
||||
}
|
||||
return f.memFiler.CreateEntry(ctx, in, opts...)
|
||||
}
|
||||
|
||||
// seedOwnedTable registers an existing table owned by owner.
|
||||
func seedOwnedTable(fc *memFiler, bucket, namespace, tableName, owner string) {
|
||||
internal := map[string]any{
|
||||
"name": tableName,
|
||||
"namespace": namespace,
|
||||
"format": "ICEBERG",
|
||||
"ownerAccountId": owner,
|
||||
"versionToken": "v1",
|
||||
"metadataVersion": 1,
|
||||
"metadataLocation": "s3://" + bucket + "/" + namespace + "/" + tableName + "/metadata/v1.metadata.json",
|
||||
"metadata": s3tables.TableMetadata{
|
||||
Iceberg: &s3tables.IcebergMetadata{TableUUID: "00000000-0000-0000-0000-000000000001"},
|
||||
},
|
||||
}
|
||||
metaBytes, _ := json.Marshal(internal)
|
||||
fc.seed(s3tables.GetTablePath(bucket, namespace, tableName), &filer_pb.Entry{
|
||||
Name: tableName,
|
||||
IsDirectory: true,
|
||||
Extended: map[string][]byte{s3tables.ExtendedKeyMetadata: metaBytes},
|
||||
})
|
||||
}
|
||||
|
||||
// seedOwnedView registers an existing view owned by owner.
|
||||
func seedOwnedView(fc *memFiler, bucket, namespace, viewName, owner string, fullMetadata []byte) {
|
||||
internal := map[string]any{
|
||||
"name": viewName,
|
||||
"namespace": namespace,
|
||||
"format": "ICEBERG",
|
||||
"ownerAccountId": owner,
|
||||
"versionToken": "v1",
|
||||
"metadataVersion": 1,
|
||||
"metadataLocation": "s3://" + bucket + "/" + namespace + "/" + viewName + "/metadata/v1.metadata.json",
|
||||
}
|
||||
if len(fullMetadata) > 0 {
|
||||
internal["metadata"] = s3tables.TableMetadata{FullMetadata: fullMetadata}
|
||||
}
|
||||
metaBytes, _ := json.Marshal(internal)
|
||||
fc.seed(s3tables.GetTablePath(bucket, namespace, viewName), &filer_pb.Entry{
|
||||
Name: viewName,
|
||||
IsDirectory: true,
|
||||
Extended: map[string][]byte{
|
||||
s3tables.ExtendedKeyMetadata: metaBytes,
|
||||
s3tables.ExtendedKeyEntryType: []byte(s3tables.EntryTypeView),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// withActions gives the request an identity allowed only the listed actions.
|
||||
func withActions(r *http.Request, name string, actions ...string) *http.Request {
|
||||
ctx := s3_constants.SetIdentityNameInContext(r.Context(), name)
|
||||
return r.WithContext(s3_constants.SetIdentityInContext(ctx, &struct {
|
||||
Name string
|
||||
Actions []string
|
||||
}{Name: name, Actions: actions}))
|
||||
}
|
||||
|
||||
func viewMetadataJSON(t *testing.T, location string) []byte {
|
||||
t.Helper()
|
||||
schema := iceberg.NewSchemaWithIdentifiers(0, nil,
|
||||
iceberg.NestedField{ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int32, Required: true})
|
||||
ver, err := view.NewVersionFromSQL(1, schema.ID, "SELECT 1", table.Identifier{"finance"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
md, err := view.NewMetadata(ver, schema, location, iceberg.Properties{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fullMetadata, err := json.Marshal(md)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return fullMetadata
|
||||
}
|
||||
|
||||
// A caller that may load a table but not commit to it must be refused before
|
||||
// the commit stages its metadata file in the table's directory. The commit
|
||||
// paths used to write that file, reach the UpdateTable authorization, and
|
||||
// delete the file again on the way out.
|
||||
func TestCommitDeniedBeforeStagingMetadata(t *testing.T) {
|
||||
const bucket = "warehouse"
|
||||
cases := map[string]func(s *Server) *httptest.ResponseRecorder{
|
||||
"commit-table": func(s *Server) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/tables/quarterly_reports",
|
||||
strings.NewReader(`{"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}`))
|
||||
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "table": "quarterly_reports"})
|
||||
w := httptest.NewRecorder()
|
||||
s.handleUpdateTable(w, withActions(r, "reader", "s3tables:GetTable"))
|
||||
return w
|
||||
},
|
||||
"commit-transaction": func(s *Server) *httptest.ResponseRecorder {
|
||||
body := `{"table-changes":[{"identifier":{"namespace":["finance"],"name":"quarterly_reports"},"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}]}`
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/transactions/commit", strings.NewReader(body))
|
||||
r = mux.SetURLVars(r, map[string]string{"prefix": bucket})
|
||||
w := httptest.NewRecorder()
|
||||
s.handleCommitTransaction(w, withActions(r, "reader", "s3tables:GetTable"))
|
||||
return w
|
||||
},
|
||||
"commit-view": func(s *Server) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/views/quarterly_view",
|
||||
strings.NewReader(`{"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}`))
|
||||
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "view": "quarterly_view"})
|
||||
w := httptest.NewRecorder()
|
||||
s.handleUpdateView(w, withActions(r, "reader", "s3tables:GetView"))
|
||||
return w
|
||||
},
|
||||
}
|
||||
for name, run := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
fc := &writeLogFiler{memFiler: newMemFiler()}
|
||||
seedNamespace(fc.memFiler, bucket, "finance", "alice")
|
||||
seedOwnedTable(fc.memFiler, bucket, "finance", "quarterly_reports", "alice")
|
||||
seedOwnedView(fc.memFiler, bucket, "finance", "quarterly_view", "alice", viewMetadataJSON(t, "s3://"+bucket+"/finance/quarterly_view"))
|
||||
s := NewServer(fc, nil)
|
||||
|
||||
w := run(s)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("status = %d, want %d (body: %s)", w.Code, http.StatusForbidden, w.Body.String())
|
||||
}
|
||||
if len(fc.created) != 0 {
|
||||
t.Errorf("refused commit wrote %v", fc.created)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The owner, and a caller whose own identity carries UpdateTable, still
|
||||
// stage their metadata file and land the commit.
|
||||
func TestCommitAllowedStagesMetadata(t *testing.T) {
|
||||
const bucket = "warehouse"
|
||||
callers := map[string]func(r *http.Request) *http.Request{
|
||||
"owner": func(r *http.Request) *http.Request {
|
||||
return r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))
|
||||
},
|
||||
"identity-actions": func(r *http.Request) *http.Request {
|
||||
return withActions(r, "writer", "s3tables:GetTable", "s3tables:UpdateTable")
|
||||
},
|
||||
}
|
||||
for name, as := range callers {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
fc := &writeLogFiler{memFiler: newMemFiler()}
|
||||
seedNamespace(fc.memFiler, bucket, "finance", "alice")
|
||||
seedOwnedTable(fc.memFiler, bucket, "finance", "quarterly_reports", "alice")
|
||||
s := NewServer(fc, nil)
|
||||
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/tables/quarterly_reports",
|
||||
strings.NewReader(`{"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}`))
|
||||
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "table": "quarterly_reports"})
|
||||
w := httptest.NewRecorder()
|
||||
s.handleUpdateTable(w, as(r))
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d (body: %s)", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
if len(fc.created) != 1 || !strings.HasSuffix(fc.created[0], ".metadata.json") {
|
||||
t.Fatalf("created = %v, want one metadata file", fc.created)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Same staging gate on the view commit path: the owner, and a caller whose own
|
||||
// identity carries UpdateView, stage a metadata file and land the commit.
|
||||
func TestViewCommitAllowedStagesMetadata(t *testing.T) {
|
||||
const bucket = "warehouse"
|
||||
fullMetadata := viewMetadataJSON(t, "s3://"+bucket+"/finance/quarterly_view")
|
||||
|
||||
callers := map[string]func(r *http.Request) *http.Request{
|
||||
"owner": func(r *http.Request) *http.Request {
|
||||
return r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))
|
||||
},
|
||||
"identity-actions": func(r *http.Request) *http.Request {
|
||||
return withActions(r, "writer", "s3tables:GetView", "s3tables:UpdateView")
|
||||
},
|
||||
}
|
||||
for name, as := range callers {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
fc := &writeLogFiler{memFiler: newMemFiler()}
|
||||
seedNamespace(fc.memFiler, bucket, "finance", "alice")
|
||||
seedOwnedView(fc.memFiler, bucket, "finance", "quarterly_view", "alice", fullMetadata)
|
||||
s := NewServer(fc, nil)
|
||||
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/views/quarterly_view",
|
||||
strings.NewReader(`{"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}`))
|
||||
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "view": "quarterly_view"})
|
||||
w := httptest.NewRecorder()
|
||||
s.handleUpdateView(w, as(r))
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d (body: %s)", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
if len(fc.created) != 1 || !strings.HasSuffix(fc.created[0], ".metadata.json") {
|
||||
t.Fatalf("created = %v, want one metadata file", fc.created)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
func TestLogManagerErrorRefusalsAreNotErrors(t *testing.T) {
|
||||
var refusals, faults []string
|
||||
oldR, oldF := logManagerRefusal, logManagerFault
|
||||
logManagerRefusal = func(f string, a ...interface{}) { refusals = append(refusals, fmt.Sprintf(f, a...)) }
|
||||
logManagerFault = func(f string, a ...interface{}) { faults = append(faults, fmt.Sprintf(f, a...)) }
|
||||
defer func() { logManagerRefusal, logManagerFault = oldR, oldF }()
|
||||
for _, c := range []struct {
|
||||
err error
|
||||
fault bool
|
||||
}{
|
||||
{&s3tables.S3TablesError{Type: s3tables.ErrCodeAccessDenied, Message: "not authorized to create namespace in this bucket"}, false},
|
||||
{&s3tables.S3TablesError{Type: s3tables.ErrCodeNoSuchNamespace, Message: "no such namespace"}, false},
|
||||
{&s3tables.S3TablesError{Type: s3tables.ErrCodeNamespaceAlreadyExists, Message: "exists"}, false},
|
||||
{errors.New("filer: connection refused"), true}, // positive control: a real fault stays at ERROR
|
||||
} {
|
||||
refusals, faults = nil, nil
|
||||
logManagerError("CreateNamespace", c.err)
|
||||
wantFaults, wantRefusals := 0, 1
|
||||
if c.fault {
|
||||
wantFaults, wantRefusals = 1, 0
|
||||
}
|
||||
if len(faults) != wantFaults || len(refusals) != wantRefusals {
|
||||
t.Errorf("%v: %d ERROR and %d refusal log(s), want %d and %d (refusals %v, faults %v)", c.err, len(faults), len(refusals), wantFaults, wantRefusals, refusals, faults)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -269,10 +269,9 @@ func (s *Server) Auth(handler http.HandlerFunc) http.HandlerFunc {
|
||||
// The auth scheme is case-insensitive (RFC 7235), matching
|
||||
// authenticateBearer below.
|
||||
if strings.HasPrefix(strings.ToLower(r.Header.Get("Authorization")), "bearer ") {
|
||||
if identityName, identity, accessKey, ok := s.authenticateBearerKey(r); ok {
|
||||
if identityName, identity, ok := s.authenticateBearer(r); ok {
|
||||
ctx := r.Context()
|
||||
ctx = s3_constants.SetIdentityNameInContext(ctx, identityName)
|
||||
ctx = s3_constants.SetAccessKeyIdInContext(ctx, accessKey)
|
||||
if identity != nil {
|
||||
ctx = s3_constants.SetIdentityInContext(ctx, identity)
|
||||
}
|
||||
@@ -291,9 +290,6 @@ func (s *Server) Auth(handler http.HandlerFunc) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
// The verifier records the key of the credential that matched into
|
||||
// this holder; the vended credentials name it.
|
||||
r = s3_constants.EnsureIdentityHolder(r)
|
||||
identityName, identity, errCode := s.authenticator.AuthenticateRequest(r)
|
||||
if errCode != s3err.ErrNone {
|
||||
apiErr := s3err.GetAPIError(errCode)
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// keyedS3Authenticator accepts every SigV4 request as one identity and records
|
||||
// the key that verified into the request's holder, as S3ApiServer's verifiers do.
|
||||
type keyedS3Authenticator struct {
|
||||
mockS3Authenticator
|
||||
accessKey string
|
||||
}
|
||||
|
||||
func (k *keyedS3Authenticator) AuthenticateRequest(r *http.Request) (string, interface{}, s3err.ErrorCode) {
|
||||
s3_constants.RecordAccessKeyId(r.Context(), k.accessKey)
|
||||
return "shared-identity", "identity-object", s3err.ErrNone
|
||||
}
|
||||
|
||||
// A catalog token is minted from one access key; the request it authenticates
|
||||
// carries that key, so the credentials it vends can name it.
|
||||
func TestAuthBearerRecordsTheTokensAccessKey(t *testing.T) {
|
||||
s, _ := newAuthTestServer()
|
||||
now := time.Now()
|
||||
token := mintTestToken(t, "AKID123", "secret456", now, now.Add(time.Hour))
|
||||
|
||||
var gotKey, gotName string
|
||||
handler := s.Auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotKey = s3_constants.GetAccessKeyIdFromContext(r)
|
||||
gotName = s3_constants.GetIdentityNameFromContext(r)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/namespaces", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("valid Bearer: status = %d, want 200", rec.Code)
|
||||
}
|
||||
if gotName != "testuser" {
|
||||
t.Errorf("identity = %q, want testuser", gotName)
|
||||
}
|
||||
if gotKey != "AKID123" {
|
||||
t.Errorf("access key in context = %q, want AKID123", gotKey)
|
||||
}
|
||||
}
|
||||
|
||||
// A SigV4-signed catalog request carries the key its authenticator verified.
|
||||
func TestAuthSigV4RecordsTheAuthenticatorsAccessKey(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
s.authenticator = &keyedS3Authenticator{accessKey: "AKIDSIGV4"}
|
||||
|
||||
var gotKey string
|
||||
handler := s.Auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotKey = s3_constants.GetAccessKeyIdFromContext(r)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/namespaces", nil)
|
||||
req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential=AKIDSIGV4/20261016/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=00")
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
if gotKey != "AKIDSIGV4" {
|
||||
t.Errorf("access key in context = %q, want AKIDSIGV4", gotKey)
|
||||
}
|
||||
}
|
||||
|
||||
// An authenticator that records no key leaves the context without one.
|
||||
func TestAuthSigV4WithoutKeyAuthenticatorRecordsNoKey(t *testing.T) {
|
||||
s := newTestServerWithOAuth()
|
||||
s.authenticator = &mockS3Authenticator{}
|
||||
|
||||
gotKey := "unset"
|
||||
handler := s.Auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotKey = s3_constants.GetAccessKeyIdFromContext(r)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/namespaces", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
if gotKey != "" {
|
||||
t.Errorf("access key in context = %q, want none", gotKey)
|
||||
}
|
||||
}
|
||||
+16
-35
@@ -158,9 +158,7 @@ func nameValidationError(err error) bool {
|
||||
// errors (400) and must carry the reason -- a variant field without
|
||||
// format-version 3 otherwise reads as a bare 500 with "variant is not supported
|
||||
// until v3" only in the log. Anything else is a server fault (500).
|
||||
// classifyManagerError maps a storage-layer error to the HTTP status, the
|
||||
// Iceberg error type and the message the catalog answers with.
|
||||
func classifyManagerError(err error) (int, string, string) {
|
||||
func writeManagerError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case nameValidationError(err),
|
||||
errors.Is(err, iceberg.ErrInvalidSchema),
|
||||
@@ -168,7 +166,8 @@ func classifyManagerError(err error) (int, string, string) {
|
||||
errors.Is(err, iceberg.ErrInvalidTypeString),
|
||||
errors.Is(err, iceberg.ErrInvalidTransform),
|
||||
errors.Is(err, iceberg.ErrInvalidArgument):
|
||||
return http.StatusBadRequest, "BadRequestException", err.Error()
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", err.Error())
|
||||
return
|
||||
}
|
||||
// Storage-layer failures are mostly the client's, not the server's. Reporting
|
||||
// a missing namespace or a name conflict as a 500 makes the catalog look
|
||||
@@ -180,49 +179,31 @@ func classifyManagerError(err error) (int, string, string) {
|
||||
// The storage-layer message names the resolved bucket, which for a
|
||||
// client that sent no warehouse at all is the default one it never
|
||||
// asked for, so say how to select a real table bucket.
|
||||
return http.StatusNotFound, "NoSuchNamespaceException",
|
||||
fmt.Sprintf("%s: each table bucket is a separate catalog, select one with warehouse=s3://<table-bucket>/ or /v1/<table-bucket>/", tableErr.Message)
|
||||
writeError(w, http.StatusNotFound, "NoSuchNamespaceException",
|
||||
fmt.Sprintf("%s: each table bucket is a separate catalog, select one with warehouse=s3://<table-bucket>/ or /v1/<table-bucket>/", tableErr.Message))
|
||||
case s3tables.ErrCodeNoSuchNamespace:
|
||||
return http.StatusNotFound, "NoSuchNamespaceException", tableErr.Message
|
||||
writeError(w, http.StatusNotFound, "NoSuchNamespaceException", tableErr.Message)
|
||||
case s3tables.ErrCodeNoSuchTable:
|
||||
return http.StatusNotFound, "NoSuchTableException", tableErr.Message
|
||||
writeError(w, http.StatusNotFound, "NoSuchTableException", tableErr.Message)
|
||||
case s3tables.ErrCodeNoSuchView:
|
||||
return http.StatusNotFound, "NoSuchViewException", tableErr.Message
|
||||
writeError(w, http.StatusNotFound, "NoSuchViewException", tableErr.Message)
|
||||
case s3tables.ErrCodeNamespaceAlreadyExists, s3tables.ErrCodeBucketAlreadyExists,
|
||||
s3tables.ErrCodeTableAlreadyExists, s3tables.ErrCodeViewAlreadyExists:
|
||||
return http.StatusConflict, "AlreadyExistsException", tableErr.Message
|
||||
writeError(w, http.StatusConflict, "AlreadyExistsException", tableErr.Message)
|
||||
case s3tables.ErrCodeNamespaceNotEmpty, s3tables.ErrCodeBucketNotEmpty:
|
||||
return http.StatusConflict, "AlreadyExistsException", tableErr.Message
|
||||
writeError(w, http.StatusConflict, "AlreadyExistsException", tableErr.Message)
|
||||
case s3tables.ErrCodeConflict:
|
||||
return http.StatusConflict, "CommitFailedException", tableErr.Message
|
||||
writeError(w, http.StatusConflict, "CommitFailedException", tableErr.Message)
|
||||
case s3tables.ErrCodeAccessDenied:
|
||||
return http.StatusForbidden, "ForbiddenException", tableErr.Message
|
||||
writeError(w, http.StatusForbidden, "ForbiddenException", tableErr.Message)
|
||||
case s3tables.ErrCodeInvalidRequest, s3tables.ErrCodeInvalidIcebergLayout:
|
||||
return http.StatusBadRequest, "BadRequestException", tableErr.Message
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", tableErr.Message)
|
||||
default:
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
}
|
||||
}
|
||||
return http.StatusInternalServerError, "InternalServerError", err.Error()
|
||||
}
|
||||
|
||||
func writeManagerError(w http.ResponseWriter, err error) {
|
||||
status, typ, msg := classifyManagerError(err)
|
||||
writeError(w, status, typ, msg)
|
||||
}
|
||||
|
||||
// A storage-layer error the catalog answers with a 4xx (access denied, not
|
||||
// found, already exists, not empty, a conflict) is the API refusing a request
|
||||
// as intended, not a server fault; it is logged at V(1). A 5xx stays at ERROR.
|
||||
var (
|
||||
logManagerRefusal = func(format string, args ...interface{}) { glog.V(1).Infof(format, args...) }
|
||||
logManagerFault = glog.Errorf
|
||||
)
|
||||
|
||||
func logManagerError(op string, err error) {
|
||||
if status, _, _ := classifyManagerError(err); status >= 400 && status < 500 {
|
||||
logManagerRefusal("Iceberg: %s refused (%d): %v", op, status, err)
|
||||
return
|
||||
}
|
||||
logManagerFault("Iceberg: %s error: %v", op, err)
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
}
|
||||
|
||||
// resolveWarehouseBucket maps a client-supplied warehouse value to a table
|
||||
|
||||
@@ -147,27 +147,20 @@ func mintToken(identityName, accessKey, secret string, ttlSeconds int) (string,
|
||||
// authenticateBearer validates a Bearer token from the Authorization header.
|
||||
// Returns the identity name, identity object, and whether auth succeeded.
|
||||
func (s *Server) authenticateBearer(r *http.Request) (string, interface{}, bool) {
|
||||
identityName, identity, _, ok := s.authenticateBearerKey(r)
|
||||
return identityName, identity, ok
|
||||
}
|
||||
|
||||
// authenticateBearerKey is authenticateBearer that also returns the access key
|
||||
// the token was minted from (its verified access_key claim).
|
||||
func (s *Server) authenticateBearerKey(r *http.Request) (string, interface{}, string, bool) {
|
||||
auth := r.Header.Get("Authorization")
|
||||
if auth == "" {
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
if !strings.HasPrefix(strings.ToLower(auth), "bearer ") {
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
tokenString := strings.TrimSpace(auth[7:])
|
||||
if tokenString == "" {
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
if s.credentialValidator == nil {
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
// Parse the token without verification first to get the access key,
|
||||
@@ -177,17 +170,17 @@ func (s *Server) authenticateBearerKey(r *http.Request) (string, interface{}, st
|
||||
_, _, err := parser.ParseUnverified(tokenString, unverified)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("Lance OAuth: failed to parse token: %v", err)
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
if unverified.AccessKey == "" {
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
identityName, identity, secretKey, err := s.credentialValidator.GetCredentialByAccessKey(unverified.AccessKey)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("Lance OAuth: failed to get credential for access key: %v", err)
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
signingKey := deriveSigningKey(unverified.AccessKey, secretKey)
|
||||
@@ -200,12 +193,10 @@ func (s *Server) authenticateBearerKey(r *http.Request) (string, interface{}, st
|
||||
})
|
||||
if err != nil || !verified.Valid {
|
||||
glog.V(2).Infof("Lance OAuth: token verification failed: %v", err)
|
||||
return "", nil, "", false
|
||||
return "", nil, false
|
||||
}
|
||||
|
||||
// The token's signing key is derived from this access key, so a verified
|
||||
// token was minted from it.
|
||||
return identityName, identity, unverified.AccessKey, true
|
||||
return identityName, identity, true
|
||||
}
|
||||
|
||||
// authenticateApiKey validates an x-api-key header carrying an S3 credential
|
||||
|
||||
@@ -177,10 +177,9 @@ func (s *Server) Auth(handler http.HandlerFunc) http.HandlerFunc {
|
||||
// different error that clients cannot act on.
|
||||
// The auth scheme is case-insensitive (RFC 7235).
|
||||
if strings.HasPrefix(strings.ToLower(r.Header.Get("Authorization")), "bearer ") {
|
||||
if identityName, identity, accessKey, ok := s.authenticateBearerKey(r); ok {
|
||||
if identityName, identity, ok := s.authenticateBearer(r); ok {
|
||||
ctx := r.Context()
|
||||
ctx = s3_constants.SetIdentityNameInContext(ctx, identityName)
|
||||
ctx = s3_constants.SetAccessKeyIdInContext(ctx, accessKey)
|
||||
if identity != nil {
|
||||
ctx = s3_constants.SetIdentityInContext(ctx, identity)
|
||||
}
|
||||
@@ -195,10 +194,8 @@ func (s *Server) Auth(handler http.HandlerFunc) http.HandlerFunc {
|
||||
|
||||
if apiKey := r.Header.Get("x-api-key"); apiKey != "" {
|
||||
if identityName, identity, ok := s.authenticateApiKey(apiKey); ok {
|
||||
accessKey, _, _ := strings.Cut(apiKey, ":")
|
||||
ctx := r.Context()
|
||||
ctx = s3_constants.SetIdentityNameInContext(ctx, identityName)
|
||||
ctx = s3_constants.SetAccessKeyIdInContext(ctx, accessKey)
|
||||
if identity != nil {
|
||||
ctx = s3_constants.SetIdentityInContext(ctx, identity)
|
||||
}
|
||||
@@ -215,9 +212,6 @@ func (s *Server) Auth(handler http.HandlerFunc) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
// The verifier records the key of the credential that matched into
|
||||
// this holder; the vended credentials name it.
|
||||
r = s3_constants.EnsureIdentityHolder(r)
|
||||
identityName, identity, errCode := s.authenticator.AuthenticateRequest(r)
|
||||
if errCode != s3err.ErrNone {
|
||||
apiErr := s3err.GetAPIError(errCode)
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
package lance
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// keyedS3Authenticator accepts every request as one identity and records the
|
||||
// key that verified into the request's holder, as S3ApiServer's verifiers do.
|
||||
type keyedS3Authenticator struct {
|
||||
mockS3Authenticator
|
||||
accessKey string
|
||||
}
|
||||
|
||||
func (k *keyedS3Authenticator) AuthenticateRequest(r *http.Request) (string, interface{}, s3err.ErrorCode) {
|
||||
s3_constants.RecordAccessKeyId(r.Context(), k.accessKey)
|
||||
return "s3user", nil, s3err.ErrNone
|
||||
}
|
||||
|
||||
func accessKeySeenByHandler(t *testing.T, s *Server, req *http.Request) string {
|
||||
t.Helper()
|
||||
gotKey := "unset"
|
||||
handler := s.Auth(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotKey = s3_constants.GetAccessKeyIdFromContext(r)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
return gotKey
|
||||
}
|
||||
|
||||
// Each way a Lance client authenticates leaves the access key it used in the
|
||||
// request context, so the credentials it vends can name that key.
|
||||
func TestAuthRecordsTheCallersAccessKey(t *testing.T) {
|
||||
now := time.Now()
|
||||
|
||||
s := newTestServerWithOAuth()
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/namespace/$/list", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+mintTestToken(t, "AKID123", "secret456", now, now.Add(time.Hour)))
|
||||
if got := accessKeySeenByHandler(t, s, req); got != "AKID123" {
|
||||
t.Errorf("Bearer: access key in context = %q, want AKID123", got)
|
||||
}
|
||||
|
||||
req = httptest.NewRequest(http.MethodGet, "/v1/namespace/$/list", nil)
|
||||
req.Header.Set("x-api-key", "AKID123:secret456")
|
||||
if got := accessKeySeenByHandler(t, s, req); got != "AKID123" {
|
||||
t.Errorf("x-api-key: access key in context = %q, want AKID123", got)
|
||||
}
|
||||
|
||||
s.authenticator = &keyedS3Authenticator{accessKey: "AKIDSIGV4"}
|
||||
req = httptest.NewRequest(http.MethodGet, "/v1/namespace/$/list", nil)
|
||||
if got := accessKeySeenByHandler(t, s, req); got != "AKIDSIGV4" {
|
||||
t.Errorf("SigV4: access key in context = %q, want AKIDSIGV4", got)
|
||||
}
|
||||
|
||||
s.authenticator = &mockS3Authenticator{}
|
||||
req = httptest.NewRequest(http.MethodGet, "/v1/namespace/$/list", nil)
|
||||
if got := accessKeySeenByHandler(t, s, req); got != "" {
|
||||
t.Errorf("authenticator without a key: access key in context = %q, want none", got)
|
||||
}
|
||||
}
|
||||
@@ -356,7 +356,6 @@ The policy engine provides a seamless upgrade path from SeaweedFS's existing sim
|
||||
| `aws:SecureTransport` | Require HTTPS |
|
||||
| `aws:CurrentTime` | Time-based access control |
|
||||
| `s3:ExistingObjectTag/<key>` | Tag-based access control for existing objects |
|
||||
| `s3:RequestObjectTag/<key>` | Tag conditions on the tags a PUT request sets |
|
||||
| Wildcard Patterns | Support for `*` and `?` in actions and resources |
|
||||
| Principal Matching | `*`, account IDs, and user ARNs |
|
||||
|
||||
@@ -364,6 +363,7 @@ The policy engine provides a seamless upgrade path from SeaweedFS's existing sim
|
||||
|
||||
| Feature | GitHub Issue |
|
||||
|---------|--------------|
|
||||
| `s3:RequestObjectTag/<key>` | For tag conditions on PUT requests |
|
||||
| `s3:RequestObjectTagKeys` | Check which tag keys are in request |
|
||||
| `s3:x-amz-content-sha256` | Content hash condition |
|
||||
| `s3:x-amz-server-side-encryption` | SSE condition |
|
||||
|
||||
@@ -728,10 +728,6 @@ func GetConditionEvaluator(operator string) (ConditionEvaluator, error) {
|
||||
// ExistingObjectTagPrefix is the prefix for S3 policy condition keys
|
||||
const ExistingObjectTagPrefix = "s3:ExistingObjectTag/"
|
||||
|
||||
// RequestObjectTagPrefix is the prefix for condition keys on the tags a
|
||||
// request sets through the X-Amz-Tagging header.
|
||||
const RequestObjectTagPrefix = "s3:RequestObjectTag/"
|
||||
|
||||
// getConditionContextValue resolves the value(s) for a condition key.
|
||||
// For s3:ExistingObjectTag/<key> conditions, it looks up the tag in objectEntry.
|
||||
// For other condition keys, it looks up the value in contextValues.
|
||||
|
||||
@@ -3,7 +3,6 @@ package policy_engine
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -11,7 +10,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// PolicyEvaluationResult represents the result of policy evaluation
|
||||
@@ -441,10 +439,6 @@ func (engine *PolicyEngine) ExtractConditionValuesFromRequest(r *http.Request) m
|
||||
// Note: s3:ExistingObjectTag/<key> conditions are evaluated using objectEntry
|
||||
// passed to EvaluatePolicy, not extracted from the request.
|
||||
|
||||
for key, value := range requestObjectTags(r) {
|
||||
values[RequestObjectTagPrefix+key] = []string{value}
|
||||
}
|
||||
|
||||
// S3 bucket-level conditions
|
||||
if delimiter := r.URL.Query().Get("delimiter"); delimiter != "" {
|
||||
values["s3:delimiter"] = []string{delimiter}
|
||||
@@ -502,86 +496,6 @@ func (engine *PolicyEngine) ExtractConditionValuesFromRequest(r *http.Request) m
|
||||
return values
|
||||
}
|
||||
|
||||
// requestObjectTags returns the tags that X-Amz-Tagging will store on the
|
||||
// object, or nil when the handler ignores the header — otherwise a tag
|
||||
// attached to a read or to a write that never stores it would satisfy a
|
||||
// tag-conditioned policy the object cannot meet.
|
||||
func requestObjectTags(r *http.Request) map[string]string {
|
||||
tagging := r.Header.Get(s3_constants.AmzObjectTagging)
|
||||
if tagging == "" {
|
||||
return nil
|
||||
}
|
||||
if !storesRequestObjectTags(r) {
|
||||
return nil
|
||||
}
|
||||
// A malformed header is rejected by the handler with InvalidTag.
|
||||
parsed, err := url.ParseQuery(tagging)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
// putToFiler rejects a repeated key, but CopyObject stores its last
|
||||
// value, so that is the one the policy has to see.
|
||||
tags := make(map[string]string, len(parsed))
|
||||
for key, vals := range parsed {
|
||||
tags[key] = vals[len(vals)-1]
|
||||
}
|
||||
return tags
|
||||
}
|
||||
|
||||
// storesRequestObjectTags reports whether the request's handler saves the
|
||||
// X-Amz-Tagging header on the object: PutObject, a copy under
|
||||
// X-Amz-Tagging-Directive: REPLACE, and CreateMultipartUpload do; every
|
||||
// other operation — reads, deletes, part uploads, completion, tagging
|
||||
// subresources — does not.
|
||||
func storesRequestObjectTags(r *http.Request) bool {
|
||||
query := r.URL.Query()
|
||||
if r.Method == http.MethodPost {
|
||||
return query.Has("uploads") && !query.Has("uploadId")
|
||||
}
|
||||
if r.Method != http.MethodPut {
|
||||
return false
|
||||
}
|
||||
// A numeric partNumber together with uploadId routes to the part
|
||||
// handlers — with or without a copy source — which never read
|
||||
// X-Amz-Tagging.
|
||||
if query.Has("partNumber") && query.Has("uploadId") && isDigits(query.Get("partNumber")) {
|
||||
return false
|
||||
}
|
||||
// The PUT subresources route before CopyObject and never read
|
||||
// X-Amz-Tagging; any other query key — presign parameters included —
|
||||
// still reaches the object PUT handlers.
|
||||
for _, subresource := range []string{"tagging", "renameObject", "acl", "retention", "legal-hold"} {
|
||||
if query.Has(subresource) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if r.Header.Get("X-Amz-Copy-Source") != "" {
|
||||
return r.Header.Get(s3_constants.AmzObjectTaggingDirective) == "REPLACE"
|
||||
}
|
||||
if query.Has("partNumber") || query.Has("uploadId") {
|
||||
return false
|
||||
}
|
||||
// An explicit directory-marker PUT stores no tags.
|
||||
if strings.HasSuffix(r.URL.Path, "/") && r.ContentLength <= 1024 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// isDigits reports whether s is non-empty and all ASCII digits, matching the
|
||||
// partNumber route constraint.
|
||||
func isDigits(s string) bool {
|
||||
if s == "" {
|
||||
return false
|
||||
}
|
||||
for _, c := range s {
|
||||
if c < '0' || c > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// IsMultipartContinuationAction returns true for actions that do not carry
|
||||
// their own SSE header because SSE is inherited from CreateMultipartUpload.
|
||||
func IsMultipartContinuationAction(action string) bool {
|
||||
|
||||
@@ -896,161 +896,6 @@ func TestExistingObjectTagCondition(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestObjectTagCondition(t *testing.T) {
|
||||
engine := NewPolicyEngine()
|
||||
|
||||
policyJSON := `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:PutObject",
|
||||
"Resource": "arn:aws:s3:::test-bucket/*",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"s3:RequestObjectTag/department": ["engineering"]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}`
|
||||
|
||||
if err := engine.SetBucketPolicy("test-bucket", policyJSON); err != nil {
|
||||
t.Fatalf("Failed to set bucket policy: %v", err)
|
||||
}
|
||||
|
||||
copyHeaders := map[string]string{"X-Amz-Copy-Source": "/src-bucket/src-object"}
|
||||
replaceHeaders := map[string]string{
|
||||
"X-Amz-Copy-Source": "/src-bucket/src-object",
|
||||
s3_constants.AmzObjectTaggingDirective: "REPLACE",
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
target string
|
||||
headers map[string]string
|
||||
tagging string
|
||||
expected PolicyEvaluationResult
|
||||
}{
|
||||
{"matching tag allows", "", "", nil, "department=engineering", PolicyResultAllow},
|
||||
{"matching tag among others allows", "", "", nil, "project=alpha&department=engineering", PolicyResultAllow},
|
||||
{"url-encoded value is decoded", "", "", nil, "department=engin%65ering", PolicyResultAllow},
|
||||
{"other value is not allowed", "", "", nil, "department=sales", PolicyResultIndeterminate},
|
||||
{"missing tag is not allowed", "", "", nil, "project=alpha", PolicyResultIndeterminate},
|
||||
{"no tagging header is not allowed", "", "", nil, "", PolicyResultIndeterminate},
|
||||
{"malformed header is not allowed", "", "", nil, "department=engineering&%zz", PolicyResultIndeterminate},
|
||||
{"last value of a repeated key counts", "", "", nil, "department=sales&department=engineering", PolicyResultAllow},
|
||||
{"earlier value of a repeated key is ignored", "", "", nil, "department=engineering&department=sales", PolicyResultIndeterminate},
|
||||
{"header is ignored on PutObjectTagging", "", "?tagging", nil, "department=engineering", PolicyResultIndeterminate},
|
||||
{"header counts with an unrelated query parameter", "", "?foo=bar", nil, "department=engineering", PolicyResultAllow},
|
||||
{"header counts on a Signature V2 presigned PUT", "", "?AWSAccessKeyId=k&Signature=s&Expires=1", nil, "department=engineering", PolicyResultAllow},
|
||||
{"header is ignored on a renameObject subresource", "", "?renameObject", nil, "department=engineering", PolicyResultIndeterminate},
|
||||
{"header is ignored on a copy that keeps source tags", "", "", copyHeaders, "department=engineering", PolicyResultIndeterminate},
|
||||
{"header counts on a copy that replaces tags", "", "", replaceHeaders, "department=engineering", PolicyResultAllow},
|
||||
{"header is ignored on a multipart copy that replaces tags", "", "?partNumber=1&uploadId=x", replaceHeaders, "department=engineering", PolicyResultIndeterminate},
|
||||
{"header counts on a copy with a lone partNumber", "", "?partNumber=1", replaceHeaders, "department=engineering", PolicyResultAllow},
|
||||
{"header counts on a multipart create", "POST", "?uploads", nil, "department=engineering", PolicyResultAllow},
|
||||
{"header is ignored on a part upload", "", "?partNumber=1&uploadId=x", nil, "department=engineering", PolicyResultIndeterminate},
|
||||
{"header is ignored on multipart completion", "POST", "?uploadId=x", nil, "department=engineering", PolicyResultIndeterminate},
|
||||
{"header is ignored on a directory marker", "", "/", nil, "department=engineering", PolicyResultIndeterminate},
|
||||
{"header is ignored on an acl subresource", "", "?acl", nil, "department=engineering", PolicyResultIndeterminate},
|
||||
{"header is ignored on a GET", "GET", "", nil, "department=engineering", PolicyResultIndeterminate},
|
||||
{"header is ignored on a DELETE", "DELETE", "", nil, "department=engineering", PolicyResultIndeterminate},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
method := tt.method
|
||||
if method == "" {
|
||||
method = http.MethodPut
|
||||
}
|
||||
req := httptest.NewRequest(method, "/test-bucket/test-object"+tt.target, nil)
|
||||
for k, v := range tt.headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
if tt.tagging != "" {
|
||||
req.Header.Set(s3_constants.AmzObjectTagging, tt.tagging)
|
||||
}
|
||||
|
||||
args := &PolicyEvaluationArgs{
|
||||
Action: "s3:PutObject",
|
||||
Resource: "arn:aws:s3:::test-bucket/test-object",
|
||||
Principal: "*",
|
||||
Conditions: engine.ExtractConditionValuesFromRequest(req),
|
||||
}
|
||||
|
||||
if result := engine.EvaluatePolicy("test-bucket", args); result != tt.expected {
|
||||
t.Errorf("Expected %v, got %v", tt.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestObjectTagConditionDeny(t *testing.T) {
|
||||
engine := NewPolicyEngine()
|
||||
|
||||
policyJSON := `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:PutObject",
|
||||
"Resource": "arn:aws:s3:::test-bucket/*"
|
||||
},
|
||||
{
|
||||
"Effect": "Deny",
|
||||
"Principal": "*",
|
||||
"Action": "s3:PutObject",
|
||||
"Resource": "arn:aws:s3:::test-bucket/*",
|
||||
"Condition": {
|
||||
"StringNotEquals": {
|
||||
"s3:RequestObjectTag/department": ["engineering"]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}`
|
||||
|
||||
if err := engine.SetBucketPolicy("test-bucket", policyJSON); err != nil {
|
||||
t.Fatalf("Failed to set bucket policy: %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
target string
|
||||
tagging string
|
||||
expected PolicyEvaluationResult
|
||||
}{
|
||||
{"required tag passes", "", "department=engineering", PolicyResultAllow},
|
||||
{"other value is denied", "", "department=sales", PolicyResultDeny},
|
||||
{"missing tag is denied", "", "project=alpha", PolicyResultDeny},
|
||||
{"repeated key ending in another value is denied", "", "department=engineering&department=sales", PolicyResultDeny},
|
||||
{"malformed header is denied", "", "department=engineering&%zz", PolicyResultDeny},
|
||||
{"unrelated query parameter does not hide the tag", "?foo=bar", "department=sales", PolicyResultDeny},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodPut, "/test-bucket/test-object"+tt.target, nil)
|
||||
req.Header.Set(s3_constants.AmzObjectTagging, tt.tagging)
|
||||
|
||||
args := &PolicyEvaluationArgs{
|
||||
Action: "s3:PutObject",
|
||||
Resource: "arn:aws:s3:::test-bucket/test-object",
|
||||
Principal: "*",
|
||||
Conditions: engine.ExtractConditionValuesFromRequest(req),
|
||||
}
|
||||
|
||||
if result := engine.EvaluatePolicy("test-bucket", args); result != tt.expected {
|
||||
t.Errorf("Expected %v, got %v", tt.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestExistingObjectTagConditionMultipleTags tests policies with multiple tag conditions
|
||||
func TestExistingObjectTagConditionMultipleTags(t *testing.T) {
|
||||
engine := NewPolicyEngine()
|
||||
|
||||
@@ -166,25 +166,15 @@ func resolveFromQueryParameters(query url.Values, method string, hasObject bool)
|
||||
}
|
||||
}
|
||||
|
||||
// ACL operations. A versionId retargets the request at a specific
|
||||
// version, so the version ACL action applies, not the current-object one.
|
||||
// ACL operations
|
||||
if query.Has("acl") {
|
||||
versioned := hasObject && query.Get("versionId") != ""
|
||||
switch method {
|
||||
// HEAD has no acl route; it lands on HeadObjectHandler and should
|
||||
// resolve like a read — s3:GetObject, or s3:GetObjectVersion below.
|
||||
case http.MethodGet:
|
||||
if versioned {
|
||||
return s3_constants.S3_ACTION_GET_OBJECT_VERSION_ACL
|
||||
}
|
||||
case http.MethodGet, http.MethodHead:
|
||||
if hasObject {
|
||||
return s3_constants.S3_ACTION_GET_OBJECT_ACL
|
||||
}
|
||||
return s3_constants.S3_ACTION_GET_BUCKET_ACL
|
||||
case http.MethodPut:
|
||||
if versioned {
|
||||
return s3_constants.S3_ACTION_PUT_OBJECT_VERSION_ACL
|
||||
}
|
||||
if hasObject {
|
||||
return s3_constants.S3_ACTION_PUT_OBJECT_ACL
|
||||
}
|
||||
@@ -230,9 +220,6 @@ func resolveFromQueryParameters(query url.Values, method string, hasObject bool)
|
||||
// Must be checked before versionId, because GET /bucket/key?attributes&versionId=xyz
|
||||
// is a GetObjectAttributes request, not a GetObjectVersion request
|
||||
if hasObject && query.Has("attributes") && method == http.MethodGet {
|
||||
if query.Get("versionId") != "" {
|
||||
return s3_constants.S3_ACTION_GET_OBJECT_VERSION_ATTRIBUTES
|
||||
}
|
||||
return s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES
|
||||
}
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ func TestResolveS3Action_AttributesBeforeVersionId(t *testing.T) {
|
||||
method: http.MethodGet,
|
||||
baseAction: s3_constants.ACTION_READ,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_GET_OBJECT_VERSION_ATTRIBUTES,
|
||||
want: s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES,
|
||||
},
|
||||
{
|
||||
name: "versionId only GET",
|
||||
@@ -146,59 +146,6 @@ func TestResolveS3Action_VersionTagging(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// An ACL request carrying versionId targets a specific version and must
|
||||
// resolve to the version ACL action so a grant limited to the current-object
|
||||
// action cannot reach historical versions.
|
||||
func TestResolveS3Action_VersionAcl(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
object string
|
||||
query string
|
||||
want string
|
||||
}{
|
||||
{"get current acl", http.MethodGet, "key", "acl", s3_constants.S3_ACTION_GET_OBJECT_ACL},
|
||||
{"put current acl", http.MethodPut, "key", "acl", s3_constants.S3_ACTION_PUT_OBJECT_ACL},
|
||||
{"get version acl", http.MethodGet, "key", "acl&versionId=v1", s3_constants.S3_ACTION_GET_OBJECT_VERSION_ACL},
|
||||
{"head acl resolves as head object", http.MethodHead, "key", "acl", s3_constants.S3_ACTION_GET_OBJECT},
|
||||
{"head version acl resolves as head version", http.MethodHead, "key", "acl&versionId=v1", s3_constants.S3_ACTION_GET_OBJECT_VERSION},
|
||||
{"put version acl", http.MethodPut, "key", "acl&versionId=v1", s3_constants.S3_ACTION_PUT_OBJECT_VERSION_ACL},
|
||||
{"empty versionId stays current", http.MethodGet, "key", "acl&versionId=", s3_constants.S3_ACTION_GET_OBJECT_ACL},
|
||||
{"bucket acl ignores versionId", http.MethodGet, "", "acl&versionId=v1", s3_constants.S3_ACTION_GET_BUCKET_ACL},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r, _ := http.NewRequest(tt.method, "http://localhost/bucket/"+tt.object+"?"+tt.query, nil)
|
||||
if got := ResolveS3Action(r, s3_constants.ACTION_READ, "bucket", tt.object); got != tt.want {
|
||||
t.Errorf("ResolveS3Action() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An attributes request carrying versionId targets a specific version and
|
||||
// must resolve to the version attributes action.
|
||||
func TestResolveS3Action_VersionAttributes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
object string
|
||||
query string
|
||||
want string
|
||||
}{
|
||||
{"get current attributes", http.MethodGet, "key", "attributes", s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES},
|
||||
{"get version attributes", http.MethodGet, "key", "attributes&versionId=v1", s3_constants.S3_ACTION_GET_OBJECT_VERSION_ATTRIBUTES},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r, _ := http.NewRequest(tt.method, "http://localhost/bucket/"+tt.object+"?"+tt.query, nil)
|
||||
if got := ResolveS3Action(r, s3_constants.ACTION_READ, "bucket", tt.object); got != tt.want {
|
||||
t.Errorf("ResolveS3Action() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Bucket subresources registered with ACTION_ADMIN must resolve to their own
|
||||
// S3 actions so a policy granting one of them does not need s3:*, and so no
|
||||
// broader grant sweeps them in.
|
||||
|
||||
@@ -216,21 +216,10 @@ func GetBucketAndObject(r *http.Request) (bucket, object string) {
|
||||
return
|
||||
}
|
||||
|
||||
// allowBackslashInObjectKey keeps '\' a literal object-key character instead
|
||||
// of normalizing it to '/'. It is a process-wide mode set once at S3 server
|
||||
// startup; the filer only treats '/' as a path separator, so a verbatim '\'
|
||||
// stays inside one filer entry name.
|
||||
var allowBackslashInObjectKey atomic.Bool
|
||||
|
||||
func SetAllowBackslashInObjectKey(allow bool) {
|
||||
allowBackslashInObjectKey.Store(allow)
|
||||
}
|
||||
|
||||
// IsValidObjectKey rejects S3 object keys that — after the mode-dependent
|
||||
// normalization NormalizeObjectKey applies — contain a `.` or `..` path
|
||||
// segment, or embed a NUL byte. Such keys are collapsed by filepath.Join
|
||||
// inside the filer and would escape the bucket directory, so they must not
|
||||
// reach the gRPC layer.
|
||||
// IsValidObjectKey rejects S3 object keys that — after normalization
|
||||
// (backslash→slash, slash collapse) — contain a `.` or `..` path segment, or
|
||||
// embed a NUL byte. Such keys are collapsed by filepath.Join inside the filer
|
||||
// and would escape the bucket directory, so they must not reach the gRPC layer.
|
||||
// Gorilla mux URL-decodes captured vars before this runs, so `%2e%2e` is
|
||||
// already `..` here.
|
||||
func IsValidObjectKey(object string) bool {
|
||||
@@ -240,9 +229,7 @@ func IsValidObjectKey(object string) bool {
|
||||
if strings.ContainsRune(object, '\x00') {
|
||||
return false
|
||||
}
|
||||
if !allowBackslashInObjectKey.Load() {
|
||||
object = strings.ReplaceAll(object, "\\", "/")
|
||||
}
|
||||
object = strings.ReplaceAll(object, "\\", "/")
|
||||
for _, seg := range strings.Split(object, "/") {
|
||||
if seg == "." || seg == ".." {
|
||||
return false
|
||||
@@ -276,8 +263,7 @@ func IsValidPathSegment(value string) bool {
|
||||
|
||||
// NormalizeObjectKey normalizes object keys by removing duplicate slashes and converting backslashes.
|
||||
// This normalizes keys from various sources (URL path, form values, etc.) to a consistent format.
|
||||
// It also converts Windows-style backslashes to forward slashes for cross-platform compatibility,
|
||||
// unless allowBackslashInObjectKey is set.
|
||||
// It also converts Windows-style backslashes to forward slashes for cross-platform compatibility.
|
||||
// Returns keys WITHOUT leading slash to match S3 API format (e.g., "foo/bar" not "/foo/bar").
|
||||
// Preserves trailing slash if present (e.g., "foo/" stays "foo/").
|
||||
func NormalizeObjectKey(object string) string {
|
||||
@@ -285,9 +271,7 @@ func NormalizeObjectKey(object string) string {
|
||||
hasTrailingSlash := strings.HasSuffix(object, "/")
|
||||
|
||||
// Convert Windows-style backslashes to forward slashes
|
||||
if !allowBackslashInObjectKey.Load() {
|
||||
object = strings.ReplaceAll(object, "\\", "/")
|
||||
}
|
||||
object = strings.ReplaceAll(object, "\\", "/")
|
||||
object = removeDuplicateSlashes(object)
|
||||
// Remove leading slash to match S3 API format
|
||||
object = strings.TrimPrefix(object, "/")
|
||||
@@ -354,7 +338,6 @@ const (
|
||||
contextKeyIdentityClaim contextKey = "s3-identity-claim"
|
||||
contextKeyIgnoredSessionToken contextKey = "s3-ignored-session-token"
|
||||
contextKeyOriginalRequestPath contextKey = "s3-original-request-path"
|
||||
contextKeyAccessKeyId contextKey = "s3-access-key-id"
|
||||
)
|
||||
|
||||
// identityHolder is a mutable container for the authenticated identity name,
|
||||
@@ -368,7 +351,6 @@ type identityHolder struct {
|
||||
name atomic.Pointer[string]
|
||||
principalArn atomic.Pointer[string]
|
||||
identityClaim atomic.Pointer[string]
|
||||
accessKeyId atomic.Pointer[string]
|
||||
}
|
||||
|
||||
// EnsureIdentityHolder attaches a mutable identity holder to the request context
|
||||
@@ -498,62 +480,6 @@ func GetOriginalRequestPathFromContext(r *http.Request) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// SetAccessKeyIdInContext stores the access key id the request authenticated
|
||||
// with: a static key's id, or an STS session's temporary key id. Several keys
|
||||
// can belong to one identity, so the identity name alone cannot tell their
|
||||
// holders apart in the audit log. An access key id is not a secret (AWS logs
|
||||
// it in CloudTrail); the secret key never reaches the context.
|
||||
func SetAccessKeyIdInContext(ctx context.Context, accessKeyId string) context.Context {
|
||||
if accessKeyId == "" {
|
||||
return ctx
|
||||
}
|
||||
if h, ok := ctx.Value(contextKeyIdentityHolder).(*identityHolder); ok && h != nil {
|
||||
h.accessKeyId.Store(&accessKeyId)
|
||||
}
|
||||
return context.WithValue(ctx, contextKeyAccessKeyId, accessKeyId)
|
||||
}
|
||||
|
||||
// RecordAccessKeyId stores the access key id of a credential whose signature
|
||||
// was just verified into the request's identity holder, so the outer
|
||||
// middleware (the audit fallback) and the handler both see it. A no-op without
|
||||
// a holder (EnsureIdentityHolder) or without a key. Only a verifier calls it:
|
||||
// the key comes from the credential that matched, never from re-reading the
|
||||
// request, whose shape the verifier already resolved.
|
||||
func RecordAccessKeyId(ctx context.Context, accessKeyId string) {
|
||||
if ctx == nil || accessKeyId == "" {
|
||||
return
|
||||
}
|
||||
if h, ok := ctx.Value(contextKeyIdentityHolder).(*identityHolder); ok && h != nil {
|
||||
h.accessKeyId.Store(&accessKeyId)
|
||||
}
|
||||
}
|
||||
|
||||
// GetAccessKeyIdFromContext retrieves the access key id the request
|
||||
// authenticated with, or "" when it carried none (anonymous, OIDC bearer).
|
||||
func GetAccessKeyIdFromContext(r *http.Request) string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
return AccessKeyIdFromContext(r.Context())
|
||||
}
|
||||
|
||||
// AccessKeyIdFromContext is GetAccessKeyIdFromContext for code that holds
|
||||
// only the request's context, such as the Iceberg credential vendor.
|
||||
func AccessKeyIdFromContext(ctx context.Context) string {
|
||||
if ctx == nil {
|
||||
return ""
|
||||
}
|
||||
if id, ok := ctx.Value(contextKeyAccessKeyId).(string); ok && id != "" {
|
||||
return id
|
||||
}
|
||||
if h, ok := ctx.Value(contextKeyIdentityHolder).(*identityHolder); ok && h != nil {
|
||||
if id := h.accessKeyId.Load(); id != nil {
|
||||
return *id
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// IgnoreSessionTokenInContext marks the request's session token as tolerated
|
||||
// rather than authenticated: a statically configured access key signed the
|
||||
// request, so the token (which credential vendors like Unity Catalog emit on
|
||||
|
||||
@@ -123,54 +123,6 @@ func TestIsValidObjectKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeObjectKeyAllowBackslash(t *testing.T) {
|
||||
SetAllowBackslashInObjectKey(true)
|
||||
defer SetAllowBackslashInObjectKey(false)
|
||||
|
||||
normalizeTests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
{"backslash kept verbatim", "folder\\file.txt", "folder\\file.txt"},
|
||||
{"nested backslash kept", "folder\\sub\\file.txt", "folder\\sub\\file.txt"},
|
||||
{"trailing backslash kept", "folder\\", "folder\\"},
|
||||
{"lone backslash kept", "\\", "\\"},
|
||||
{"double backslash kept", "a\\\\b", "a\\\\b"},
|
||||
{"mixed separators", "folder\\sub/another\\file.txt", "folder\\sub/another\\file.txt"},
|
||||
{"duplicate slashes still collapse", "folder//sub///file.txt", "folder/sub/file.txt"},
|
||||
{"leading slash still trimmed", "/folder\\file.txt", "folder\\file.txt"},
|
||||
{"trailing slash preserved", "folder/", "folder/"},
|
||||
{"windows path style", "C:\\Users\\test\\file.txt", "C:\\Users\\test\\file.txt"},
|
||||
}
|
||||
for _, tt := range normalizeTests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := NormalizeObjectKey(tt.input); got != tt.expected {
|
||||
t.Errorf("NormalizeObjectKey(%q) = %q, want %q", tt.input, got, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
validTests := []struct {
|
||||
name string
|
||||
input string
|
||||
want bool
|
||||
}{
|
||||
{"backslash dotdot is one segment", "..\\evil\\test.txt", true},
|
||||
{"backslash dotdot inside", "good\\..\\evil/test.txt", true},
|
||||
{"nested dotdot still rejected", "good/../evil/test.txt", false},
|
||||
{"leading dotdot still rejected", "../evil/test.txt", false},
|
||||
{"plain backslash key", "folder\\file.txt", true},
|
||||
}
|
||||
for _, tt := range validTests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := IsValidObjectKey(tt.input); got != tt.want {
|
||||
t.Errorf("IsValidObjectKey(%q) = %v, want %v", tt.input, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsValidBucketName(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -4,22 +4,17 @@ package s3_constants
|
||||
// These match the official AWS S3 action format used in IAM and bucket policies
|
||||
const (
|
||||
// Object operations
|
||||
S3_ACTION_GET_OBJECT = "s3:GetObject"
|
||||
S3_ACTION_PUT_OBJECT = "s3:PutObject"
|
||||
S3_ACTION_DELETE_OBJECT = "s3:DeleteObject"
|
||||
S3_ACTION_DELETE_OBJECT_VERSION = "s3:DeleteObjectVersion"
|
||||
S3_ACTION_GET_OBJECT_VERSION = "s3:GetObjectVersion"
|
||||
S3_ACTION_GET_OBJECT_ATTRIBUTES = "s3:GetObjectAttributes"
|
||||
S3_ACTION_GET_OBJECT_VERSION_ATTRIBUTES = "s3:GetObjectVersionAttributes"
|
||||
S3_ACTION_GET_OBJECT = "s3:GetObject"
|
||||
S3_ACTION_PUT_OBJECT = "s3:PutObject"
|
||||
S3_ACTION_DELETE_OBJECT = "s3:DeleteObject"
|
||||
S3_ACTION_DELETE_OBJECT_VERSION = "s3:DeleteObjectVersion"
|
||||
S3_ACTION_GET_OBJECT_VERSION = "s3:GetObjectVersion"
|
||||
S3_ACTION_GET_OBJECT_ATTRIBUTES = "s3:GetObjectAttributes"
|
||||
|
||||
// Object ACL operations
|
||||
S3_ACTION_GET_OBJECT_ACL = "s3:GetObjectAcl"
|
||||
S3_ACTION_PUT_OBJECT_ACL = "s3:PutObjectAcl"
|
||||
|
||||
// Version-specific ACL operations (?acl&versionId)
|
||||
S3_ACTION_GET_OBJECT_VERSION_ACL = "s3:GetObjectVersionAcl"
|
||||
S3_ACTION_PUT_OBJECT_VERSION_ACL = "s3:PutObjectVersionAcl"
|
||||
|
||||
// Object tagging operations
|
||||
S3_ACTION_GET_OBJECT_TAGGING = "s3:GetObjectTagging"
|
||||
S3_ACTION_PUT_OBJECT_TAGGING = "s3:PutObjectTagging"
|
||||
|
||||
@@ -576,97 +576,3 @@ func TestRecheckObjectAclTagConditionedPolicy(t *testing.T) {
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
s3a.recheckPolicyWithObjectEntry(putReq, "b", "secret.txt", s3_constants.S3_ACTION_PUT_OBJECT_ACL, publicEntry, "test"))
|
||||
}
|
||||
|
||||
// A versioned GetObjectAttributes request is authorized against the version
|
||||
// read grant, not the attributes action the original request resolves to: an
|
||||
// explicit bucket-policy Deny on s3:GetObjectVersion blocks it, while a legacy
|
||||
// identity holding only the coarse Read grant is still accepted.
|
||||
func TestCheckVersionReadGrant(t *testing.T) {
|
||||
s3a := &S3ApiServer{
|
||||
policyEngine: NewBucketPolicyEngine(),
|
||||
iam: &IdentityAccessManagement{},
|
||||
}
|
||||
|
||||
denyPolicyJSON := `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:*",
|
||||
"Resource": ["arn:aws:s3:::deny-bucket", "arn:aws:s3:::deny-bucket/*"]
|
||||
},
|
||||
{
|
||||
"Effect": "Deny",
|
||||
"Principal": "*",
|
||||
"Action": "s3:GetObjectVersion",
|
||||
"Resource": "arn:aws:s3:::deny-bucket/key"
|
||||
}
|
||||
]
|
||||
}`
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("deny-bucket", denyPolicyJSON))
|
||||
|
||||
allowPolicyJSON := `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:*",
|
||||
"Resource": ["arn:aws:s3:::allow-bucket", "arn:aws:s3:::allow-bucket/*"]
|
||||
}
|
||||
]
|
||||
}`
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("allow-bucket", allowPolicyJSON))
|
||||
|
||||
identity := &Identity{
|
||||
Name: "reader",
|
||||
Actions: []Action{s3_constants.ACTION_READ},
|
||||
PrincipalArn: "arn:aws:iam::000000000000:user/reader",
|
||||
}
|
||||
|
||||
attrsReq := func(bucket string) *http.Request {
|
||||
req := httptest.NewRequest(http.MethodGet, "/"+bucket+"/key?attributes&versionId=v1", nil)
|
||||
return req.WithContext(s3_constants.SetIdentityInContext(req.Context(), identity))
|
||||
}
|
||||
|
||||
assert.Equal(t, s3err.ErrAccessDenied,
|
||||
s3a.checkVersionReadGrant(attrsReq("deny-bucket"), "deny-bucket", "key", "v1", nil))
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
s3a.checkVersionReadGrant(attrsReq("allow-bucket"), "allow-bucket", "key", "v1", nil))
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
s3a.checkVersionReadGrant(attrsReq("no-policy-bucket"), "no-policy-bucket", "key", "v1", nil))
|
||||
}
|
||||
|
||||
// Presigned-URL credentials ride along on the synthesized version-read
|
||||
// request, so an s3:authType=REST-QUERY-STRING policy condition decides the
|
||||
// recheck the same way it decided the real request.
|
||||
func TestCheckVersionReadGrantPreservesQueryAuth(t *testing.T) {
|
||||
s3a := &S3ApiServer{
|
||||
policyEngine: NewBucketPolicyEngine(),
|
||||
iam: &IdentityAccessManagement{},
|
||||
}
|
||||
|
||||
policyJSON := `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:*",
|
||||
"Resource": ["arn:aws:s3:::qs-bucket", "arn:aws:s3:::qs-bucket/*"],
|
||||
"Condition": {"StringEquals": {"s3:authType": "REST-QUERY-STRING"}}
|
||||
}]
|
||||
}`
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("qs-bucket", policyJSON))
|
||||
|
||||
presigned := httptest.NewRequest(http.MethodGet,
|
||||
"/qs-bucket/key?attributes&versionId=v1&AWSAccessKeyId=AK&Signature=sig&Expires=9999999999", nil)
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
s3a.checkVersionReadGrant(presigned, "qs-bucket", "key", "v1", nil))
|
||||
|
||||
keyReq := objectKeyPolicyRequest(presigned, http.MethodGet, "qs-bucket", "key", "v1")
|
||||
q := keyReq.URL.Query()
|
||||
assert.Equal(t, "AK", q.Get("AWSAccessKeyId"))
|
||||
assert.Equal(t, "v1", q.Get("versionId"))
|
||||
assert.False(t, q.Has("attributes"))
|
||||
}
|
||||
@@ -2609,8 +2609,8 @@ func (e *EmbeddedIamApi) handleImplicitUsername(r *http.Request, values url.Valu
|
||||
}
|
||||
}
|
||||
|
||||
// iamSelfServiceActions are actions that users can perform on their own resources without admin rights,
|
||||
// unless selfServiceRequiresGrant is set, in which case they need an iam:<Action> grant like any other.
|
||||
// iamSelfServiceActions are actions that users can perform on their own resources without admin rights.
|
||||
// According to AWS IAM, users can manage their own access keys without requiring full admin permissions.
|
||||
var iamSelfServiceActions = map[string]bool{
|
||||
"CreateAccessKey": true,
|
||||
"DeleteAccessKey": true,
|
||||
@@ -2656,18 +2656,15 @@ func iamTargetUserName(action string, r *http.Request) string {
|
||||
// data-plane policy, which says nothing about administering the credential
|
||||
// store.
|
||||
//
|
||||
// By default users may run self-service actions against their own identity
|
||||
// without any IAM grant. With selfServiceRequiresGrant set they need the
|
||||
// iam:<Action> grant as AWS requires, authorized against the target user's
|
||||
// ARN (the caller's own when UserName is empty), so a policy can confine it
|
||||
// to the caller's own keys.
|
||||
// Users may run self-service actions against their own identity without any
|
||||
// IAM grant, matching AWS.
|
||||
func (iam *IdentityAccessManagement) AuthorizeIamAction(r *http.Request, identity *Identity, action, targetUserName string) s3err.ErrorCode {
|
||||
// The anonymous identity has no user of its own, so every self-service
|
||||
// action it names would run against someone else's.
|
||||
if identity == nil || identity.Name == s3_constants.AccountAnonymousId {
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
if !iam.selfServiceRequiresGrant && iamRequiresAdminForOthers(action) && (targetUserName == "" || targetUserName == identity.Name) {
|
||||
if iamRequiresAdminForOthers(action) && (targetUserName == "" || targetUserName == identity.Name) {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if identity.isAdmin() {
|
||||
@@ -2680,13 +2677,6 @@ func (iam *IdentityAccessManagement) AuthorizeIamAction(r *http.Request, identit
|
||||
if iamRequiresSelfTarget(action) && targetUserName != "" {
|
||||
resource = fmt.Sprintf("arn:aws:iam:::user/%s", targetUserName)
|
||||
}
|
||||
if iam.selfServiceRequiresGrant && iamRequiresAdminForOthers(action) {
|
||||
target := targetUserName
|
||||
if target == "" {
|
||||
target = identity.Name
|
||||
}
|
||||
resource = fmt.Sprintf("arn:aws:iam:::user/%s", target)
|
||||
}
|
||||
return iam.VerifyActionPermission(r, identity, Action("iam:"+action), resource, "")
|
||||
}
|
||||
|
||||
|
||||
@@ -145,75 +145,3 @@ func TestAuthorizeIamActionCreateServiceAccountScopedByPolicyResource(t *testing
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
iam.AuthorizeIamAction(iamPostRequest(""), admin, "CreateServiceAccount", "victim"))
|
||||
}
|
||||
|
||||
var iamSelfServiceActionNames = []string{"CreateAccessKey", "DeleteAccessKey", "UpdateAccessKey", "ListAccessKeys", "GetUser"}
|
||||
|
||||
func ownKeysPolicy(resource string) string {
|
||||
return `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["iam:CreateAccessKey","iam:DeleteAccessKey","iam:UpdateAccessKey","iam:ListAccessKeys","iam:GetUser"],"Resource":["` + resource + `"]}]}`
|
||||
}
|
||||
|
||||
// With selfServiceRequiresGrant, an identity holding only data-plane rights may
|
||||
// no longer manage its own access keys: a leaked key cannot mint further keys
|
||||
// that outlive its own revocation, nor deactivate the keys it was issued.
|
||||
func TestAuthorizeIamActionSelfServiceRequiresGrantWhenConfigured(t *testing.T) {
|
||||
iam := newIamAuthzTestIam(t)
|
||||
iam.selfServiceRequiresGrant = true
|
||||
powerUser := &Identity{Name: "power_user", PolicyNames: []string{"PowerUserPolicy"}}
|
||||
bare := &Identity{Name: "bare_user"}
|
||||
|
||||
for _, action := range iamSelfServiceActionNames {
|
||||
for _, identity := range []*Identity{powerUser, bare} {
|
||||
for _, target := range []string{"", identity.Name, "victim"} {
|
||||
assert.Equal(t, s3err.ErrAccessDenied, iam.AuthorizeIamAction(iamPostRequest(""), identity, action, target),
|
||||
"%s by %s on %q", action, identity.Name, target)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The grant is authorized against the target user's ARN, the caller's own when
|
||||
// UserName is empty, so a policy can confine it to the caller's own keys.
|
||||
func TestAuthorizeIamActionSelfServiceGrantIsScopedByResource(t *testing.T) {
|
||||
for _, resource := range []string{"arn:aws:iam:::user/key_owner", "arn:aws:iam:::user/${aws:username}"} {
|
||||
t.Run(resource, func(t *testing.T) {
|
||||
iam := newIamAuthzTestIam(t)
|
||||
iam.selfServiceRequiresGrant = true
|
||||
require.NoError(t, iam.PutPolicy("OwnKeysPolicy", ownKeysPolicy(resource)))
|
||||
owner := &Identity{Name: "key_owner", PolicyNames: []string{"OwnKeysPolicy"}}
|
||||
|
||||
for _, action := range iamSelfServiceActionNames {
|
||||
assert.Equal(t, s3err.ErrNone, iam.AuthorizeIamAction(iamPostRequest(""), owner, action, ""), "%s on itself, implicit", action)
|
||||
assert.Equal(t, s3err.ErrNone, iam.AuthorizeIamAction(iamPostRequest(""), owner, action, "key_owner"), "%s on itself", action)
|
||||
assert.Equal(t, s3err.ErrAccessDenied, iam.AuthorizeIamAction(iamPostRequest(""), owner, action, "victim"), "%s on another user", action)
|
||||
}
|
||||
assert.Equal(t, s3err.ErrAccessDenied, iam.AuthorizeIamAction(iamPostRequest(""), owner, "CreateUser", "victim"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The setting changes nothing for the admin, nor for an iam:* grant.
|
||||
func TestAuthorizeIamActionSelfServiceRequiresGrantKeepsAdmin(t *testing.T) {
|
||||
iam := newIamAuthzTestIam(t)
|
||||
iam.selfServiceRequiresGrant = true
|
||||
admin := &Identity{Name: "admin", Actions: []Action{s3_constants.ACTION_ADMIN}}
|
||||
operator := &Identity{Name: "iam_operator", PolicyNames: []string{"IamAdminPolicy"}}
|
||||
|
||||
for _, action := range iamSelfServiceActionNames {
|
||||
for _, identity := range []*Identity{admin, operator} {
|
||||
for _, target := range []string{"", identity.Name, "victim"} {
|
||||
assert.Equal(t, s3err.ErrNone, iam.AuthorizeIamAction(iamPostRequest(""), identity, action, target),
|
||||
"%s by %s on %q", action, identity.Name, target)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Off by default: self-service stays allowed without a grant.
|
||||
func TestAuthorizeIamActionSelfServiceDefaultUnchanged(t *testing.T) {
|
||||
iam := newIamAuthzTestIam(t)
|
||||
powerUser := &Identity{Name: "power_user", PolicyNames: []string{"PowerUserPolicy"}}
|
||||
for _, action := range iamSelfServiceActionNames {
|
||||
assert.Equal(t, s3err.ErrNone, iam.AuthorizeIamAction(iamPostRequest(""), powerUser, action, ""), action)
|
||||
assert.Equal(t, s3err.ErrNone, iam.AuthorizeIamAction(iamPostRequest(""), powerUser, action, "power_user"), action)
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,12 @@ package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// icebergVendedCredentialsProvider names the origin recorded on sessions the
|
||||
@@ -37,11 +34,6 @@ type VendedCredentials struct {
|
||||
// has already authenticated and authorized. Returns nil when no role is
|
||||
// configured, which leaves the catalog telling the client to keep using its
|
||||
// own credentials.
|
||||
//
|
||||
// The access key the caller authenticated with (from ctx) is recorded in the
|
||||
// session: a short hash of it ends the session name, so the audit log's
|
||||
// requester_arn tells apart the holders of several keys on one identity, and
|
||||
// the key id itself is carried in the session token.
|
||||
func (s3a *S3ApiServer) VendTableCredentials(ctx context.Context, principal, bucket, prefix string, readOnly bool) (*VendedCredentials, error) {
|
||||
if s3a.icebergCredentialRole == "" {
|
||||
return nil, nil
|
||||
@@ -63,14 +55,12 @@ func (s3a *S3ApiServer) VendTableCredentials(ctx context.Context, principal, buc
|
||||
return nil, err
|
||||
}
|
||||
|
||||
accessKey := s3_constants.AccessKeyIdFromContext(ctx)
|
||||
request := &sts.AssumeRoleForPrincipalRequest{
|
||||
RoleArn: s3a.icebergCredentialRole,
|
||||
Principal: principal,
|
||||
RoleSessionName: icebergSessionName(principal, bucket, prefix, accessKey),
|
||||
ProviderName: icebergVendedCredentialsProvider,
|
||||
Policy: &policy,
|
||||
SourceAccessKeyId: accessKey,
|
||||
RoleArn: s3a.icebergCredentialRole,
|
||||
Principal: principal,
|
||||
RoleSessionName: icebergSessionName(principal, bucket, prefix),
|
||||
ProviderName: icebergVendedCredentialsProvider,
|
||||
Policy: &policy,
|
||||
}
|
||||
if s3a.icebergCredentialDuration > 0 {
|
||||
duration := s3a.icebergCredentialDuration
|
||||
@@ -172,25 +162,9 @@ func tablePrefixSessionPolicy(bucket, prefix string, readOnly bool) (string, err
|
||||
return string(encoded), nil
|
||||
}
|
||||
|
||||
// icebergSessionKeyTagLength is the hex length of the access key hash that ends
|
||||
// a vended session's name: 48 bits, so two keys of one identity collide with
|
||||
// odds of about 2^-48.
|
||||
const icebergSessionKeyTagLength = 12
|
||||
|
||||
// icebergSessionKeyTag is "-k" and the first icebergSessionKeyTagLength hex
|
||||
// digits of the SHA-256 of the access key id, or "" without a key.
|
||||
func icebergSessionKeyTag(accessKey string) string {
|
||||
if accessKey == "" {
|
||||
return ""
|
||||
}
|
||||
sum := sha256.Sum256([]byte(accessKey))
|
||||
return "-k" + hex.EncodeToString(sum[:])[:icebergSessionKeyTagLength]
|
||||
}
|
||||
|
||||
// icebergSessionName builds a session name that identifies the caller, the
|
||||
// table and the caller's access key in audit logs, within the 64-character AWS
|
||||
// limit. The key tag is never cut: the table part gives way to it.
|
||||
func icebergSessionName(principal, bucket, prefix, accessKey string) string {
|
||||
// icebergSessionName builds a session name that identifies the caller and the
|
||||
// table in audit logs, within the 64-character AWS limit.
|
||||
func icebergSessionName(principal, bucket, prefix string) string {
|
||||
name := fmt.Sprintf("iceberg-%s-%s", principal, strings.ReplaceAll(strings.Trim(prefix, "/"), "/", "-"))
|
||||
if strings.Trim(prefix, "/") == "" {
|
||||
name = fmt.Sprintf("iceberg-%s-%s", principal, bucket)
|
||||
@@ -203,9 +177,8 @@ func icebergSessionName(principal, bucket, prefix, accessKey string) string {
|
||||
return '-'
|
||||
}
|
||||
}, name)
|
||||
tag := icebergSessionKeyTag(accessKey)
|
||||
if limit := 64 - len(tag); len(name) > limit {
|
||||
name = name[:limit]
|
||||
if len(name) > 64 {
|
||||
name = name[:64]
|
||||
}
|
||||
return name + tag
|
||||
return name
|
||||
}
|
||||
@@ -114,7 +114,7 @@ func TestTablePrefixSessionPolicyLeavesBucketLocationUnconditioned(t *testing.T)
|
||||
}
|
||||
|
||||
func TestIcebergSessionNameIsBounded(t *testing.T) {
|
||||
name := icebergSessionName(strings.Repeat("principal", 10), "warehouse", "ns/table", "")
|
||||
name := icebergSessionName(strings.Repeat("principal", 10), "warehouse", "ns/table")
|
||||
if len(name) > 64 {
|
||||
t.Errorf("session name is %d chars, want at most 64", len(name))
|
||||
}
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
func TestIcebergSessionNameWithoutKeyIsUnchanged(t *testing.T) {
|
||||
assert.Equal(t, "iceberg-analytics-ns-t", icebergSessionName("analytics", "b", "ns/t", ""))
|
||||
assert.Equal(t, "iceberg-anonymous-ns-t", icebergSessionName("anonymous", "b", "ns/t", ""))
|
||||
}
|
||||
|
||||
func TestIcebergSessionNameEndsWithTheKeyTag(t *testing.T) {
|
||||
a := icebergSessionName("analytics", "b", "ns/t", sharedKeyA)
|
||||
b := icebergSessionName("analytics", "b", "ns/t", sharedKeyB)
|
||||
assert.NotEqual(t, a, b, "two keys of one identity must give distinguishable session names")
|
||||
for _, name := range []string{a, b} {
|
||||
assert.True(t, strings.HasPrefix(name, "iceberg-analytics-ns-t-k"), name)
|
||||
assert.Len(t, name, len("iceberg-analytics-ns-t-k")+icebergSessionKeyTagLength)
|
||||
}
|
||||
assert.Equal(t, a, icebergSessionName("analytics", "b", "ns/t", sharedKeyA), "the tag is stable")
|
||||
assert.NotContains(t, a, sharedKeyA, "the name carries a hash, not the key id")
|
||||
}
|
||||
|
||||
// A long identity and table give way to the tag; the tag is never cut.
|
||||
func TestIcebergSessionNameKeepsTheWholeTagWithinTheLimit(t *testing.T) {
|
||||
principal := "svc-0b6f6d1c-6f1e-4c1a-9f57-3a8f4c0f1d2e"
|
||||
name := icebergSessionName(principal, "b", "a_long_namespace/a_long_table_name", sharedKeyA)
|
||||
tag := icebergSessionKeyTag(sharedKeyA)
|
||||
assert.LessOrEqual(t, len(name), 64)
|
||||
assert.True(t, strings.HasSuffix(name, tag), name)
|
||||
assert.True(t, strings.HasPrefix(name, "iceberg-"+principal), name)
|
||||
for _, r := range name {
|
||||
ok := r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_'
|
||||
assert.True(t, ok, "session name %q contains %q", name, r)
|
||||
}
|
||||
long := icebergSessionName(strings.Repeat("principal", 10), "b", "ns/t", sharedKeyB)
|
||||
assert.Len(t, long, 64)
|
||||
assert.True(t, strings.HasSuffix(long, icebergSessionKeyTag(sharedKeyB)))
|
||||
}
|
||||
|
||||
// The vendor reads the caller's key from the request context.
|
||||
func TestVendTableCredentialsReadsTheKeyFromTheContext(t *testing.T) {
|
||||
ctx := s3_constants.SetAccessKeyIdInContext(context.Background(), sharedKeyA)
|
||||
assert.Equal(t, sharedKeyA, s3_constants.AccessKeyIdFromContext(ctx))
|
||||
assert.Equal(t, "", s3_constants.AccessKeyIdFromContext(context.Background()))
|
||||
}
|
||||
|
||||
// VendTableCredentials mints a real session from the caller's key: the session
|
||||
// name ends with the key's tag and the token carries the key id.
|
||||
func TestVendTableCredentialsRecordsTheCallersKey(t *testing.T) {
|
||||
mgr := newTestIAMManager(t)
|
||||
require.NoError(t, mgr.CreateRole(context.Background(), "", "IcebergTableAccess", &integration.RoleDefinition{
|
||||
RoleName: "IcebergTableAccess",
|
||||
TrustPolicy: &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{
|
||||
Effect: "Allow",
|
||||
Principal: map[string]interface{}{"Federated": icebergVendedCredentialsProvider},
|
||||
Action: []string{"sts:AssumeRoleWithCredentials"},
|
||||
}},
|
||||
},
|
||||
}))
|
||||
iam := newSharedIdentityIAM()
|
||||
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
|
||||
s3a := &S3ApiServer{iam: iam}
|
||||
s3a.SetIcebergCredentialRole("arn:aws:iam::role/IcebergTableAccess", 3600)
|
||||
|
||||
for _, key := range []string{sharedKeyA, sharedKeyB, ""} {
|
||||
ctx := context.Background()
|
||||
if key != "" {
|
||||
// As the catalog's auth does: the holder is installed, the verifier records into it.
|
||||
r := s3_constants.EnsureIdentityHolder(httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
s3_constants.RecordAccessKeyId(r.Context(), key)
|
||||
ctx = r.Context()
|
||||
}
|
||||
creds, err := s3a.VendTableCredentials(ctx, "shared-user", "warehouse", "ns/t", false)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, creds)
|
||||
info, err := s3a.stsService().ValidateSessionToken(context.Background(), creds.SessionToken)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, key, info.SourceAccessKeyId, "key %q", key)
|
||||
assert.Equal(t, icebergSessionName("shared-user", "warehouse", "ns/t", key), info.SessionName, "key %q", key)
|
||||
if key != "" {
|
||||
assert.Contains(t, info.SessionName, icebergSessionKeyTag(key))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -238,12 +238,10 @@ func TestAnonymousObjectACLVersionedDirectoryIdentity(t *testing.T) {
|
||||
f.entries["/buckets/b/folder/.versions"] = &filer_pb.Entry{IsDirectory: true, Extended: map[string][]byte{s3_constants.ExtLatestVersionIdKey: []byte("")}}
|
||||
}
|
||||
// Equivalent filer-path spellings must not recover a different object's data.
|
||||
for _, object := range []string{"folder/", "folder//", "folder\\"} {
|
||||
assertMissing(serveAnonymousRead(s3a, method, object, route.query, headers))
|
||||
}
|
||||
assertMissing(serveAnonymousRead(s3a, method, "folder/", route.query, headers))
|
||||
// Spellings the policy's folder/ grant does not cover are
|
||||
// masked: a miss must be indistinguishable from a denied read.
|
||||
for _, object := range []string{"folder//x", "folder\\x"} {
|
||||
for _, object := range []string{"folder//", "folder\\"} {
|
||||
rr := serveAnonymousRead(s3a, method, object, route.query, headers)
|
||||
require.Equal(t, http.StatusForbidden, rr.Code, rr.Body.String())
|
||||
}
|
||||
@@ -283,40 +281,3 @@ func TestAnonymousObjectACLVersionedDirectoryIdentity(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A literal-backslash key is a different object than its slash spelling only
|
||||
// when allowBackslashInObjectKey is set. A public grant on b/folder/ must not
|
||||
// authorize an anonymous read of the separate folder\ object under that mode.
|
||||
func TestAnonymousObjectACLBackslashKeyIdentity(t *testing.T) {
|
||||
for _, allowBackslash := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("allowBackslashInKey=%v", allowBackslash), func(t *testing.T) {
|
||||
s3a, f := newAnonymousReadTestServer(t)
|
||||
s3_constants.SetAllowBackslashInObjectKey(allowBackslash)
|
||||
t.Cleanup(func() { s3_constants.SetAllowBackslashInObjectKey(false) })
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("b", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject*","Resource":"arn:aws:s3:::b/folder/"}]}`))
|
||||
slash := anonymousReadEntry([]byte(`[]`))
|
||||
slash.Name = "folder"
|
||||
slash.MarkPrefixObject()
|
||||
f.entries["/buckets/b/folder"] = slash
|
||||
backslash := anonymousReadEntry([]byte(`[]`))
|
||||
backslash.Name = `folder\`
|
||||
f.entries[`/buckets/b/folder\`] = backslash
|
||||
|
||||
rr := serveAnonymousRead(s3a, http.MethodGet, "folder/", "", nil)
|
||||
require.Equal(t, http.StatusOK, rr.Code, rr.Body.String())
|
||||
require.Equal(t, "hello world", rr.Body.String())
|
||||
|
||||
rr = serveAnonymousRead(s3a, http.MethodGet, `folder\`, "", nil)
|
||||
if !allowBackslash {
|
||||
// Default mode folds the spelling onto the slash key the policy covers.
|
||||
require.Equal(t, http.StatusOK, rr.Code, rr.Body.String())
|
||||
} else {
|
||||
require.Equal(t, http.StatusForbidden, rr.Code, rr.Body.String())
|
||||
backslash.Extended[s3_constants.ExtAmzAclKey] = anonymousReadGrant("READ")
|
||||
rr = serveAnonymousRead(s3a, http.MethodGet, `folder\`, "", nil)
|
||||
require.Equal(t, http.StatusOK, rr.Code, rr.Body.String())
|
||||
require.Equal(t, "hello world", rr.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -118,7 +118,7 @@ func (s3a *S3ApiServer) authorizeAnonymousObjectRead(r *http.Request, bucket, ob
|
||||
// public-read bucket. Anything else masks the miss as AccessDenied.
|
||||
func (s3a *S3ApiServer) authorizeAnonymousBucketList(r *http.Request, bucket string) s3err.ErrorCode {
|
||||
identity, _ := s3_constants.GetIdentityFromContext(r).(*Identity)
|
||||
object := s3_constants.NormalizeObjectKey(mux.Vars(r)["object"])
|
||||
object := mux.Vars(r)["object"]
|
||||
// The caller's query parameters would otherwise retarget these checks
|
||||
// (?policy resolves to GetBucketPolicy) or satisfy a prefix condition on an
|
||||
// unrelated subtree, so each runs on a request with a fixed shape: a
|
||||
@@ -171,12 +171,10 @@ func (s3a *S3ApiServer) authorizeAnonymousBucketList(r *http.Request, bucket str
|
||||
|
||||
// writeAnonymousAwareNotFound keeps missing-bucket and missing-key misses
|
||||
// indistinguishable from denied reads for anonymous callers: a 404 only
|
||||
// reaches the wire when the bucket is anonymously listable. The denial is
|
||||
// refined like Auth's, so a malformed bucket name answers InvalidBucketName.
|
||||
// reaches the wire when the bucket is anonymously listable.
|
||||
func (s3a *S3ApiServer) writeAnonymousAwareNotFound(w http.ResponseWriter, r *http.Request, bucket string, code s3err.ErrorCode) {
|
||||
if isAnonymousObjectRead(r) && s3a.authorizeAnonymousBucketList(r, bucket) != s3err.ErrNone {
|
||||
identity, _ := s3_constants.GetIdentityFromContext(r).(*Identity)
|
||||
s3err.WriteErrorResponse(w, r, refineDenialForBucketName(r, identity, s3err.ErrAccessDenied))
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
s3err.WriteErrorResponse(w, r, code)
|
||||
|
||||
@@ -299,9 +299,7 @@ func TestAnonymousObjectACLConfiguredIdentity(t *testing.T) {
|
||||
}{
|
||||
{"legacy anonymous permission", false, []Action{s3_constants.ACTION_READ}, "", false, 200},
|
||||
{"identity policy allow", false, nil, `{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::b/*"}`, false, 200},
|
||||
// The fixture bucket "b" is shorter than S3's three-character minimum,
|
||||
// so a denial for a resolved identity answers InvalidBucketName.
|
||||
{"identity deny beats object ACL", true, nil, `{"Effect":"Deny","Action":"s3:GetObject","Resource":"arn:aws:s3:::b/*"}`, false, 400},
|
||||
{"identity deny beats object ACL", true, nil, `{"Effect":"Deny","Action":"s3:GetObject","Resource":"arn:aws:s3:::b/*"}`, false, 403},
|
||||
{"disabled identity cannot grant", false, []Action{s3_constants.ACTION_READ}, "", true, 403},
|
||||
{"public ACL does not require identity", true, nil, "", true, 200},
|
||||
} {
|
||||
|
||||
@@ -804,7 +804,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
bucket, object := s3_constants.GetBucketAndObject(r)
|
||||
glog.V(3).Infof("GetObjectHandler %s %s", bucket, object)
|
||||
if _, err := s3a.validateTableBucketObjectPathOrVerify(bucket, object); err != nil {
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
@@ -2251,9 +2251,8 @@ func (s3a *S3ApiServer) readChunkRange(ctx context.Context, fileId string, offse
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
|
||||
err = util_http.StatusError(chunkUrl, resp)
|
||||
resp.Body.Close()
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("unexpected status code %d for chunk %s", resp.StatusCode, fileId)
|
||||
}
|
||||
|
||||
return resp.Body, nil
|
||||
@@ -2500,7 +2499,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
|
||||
bucket, object := s3_constants.GetBucketAndObject(r)
|
||||
glog.V(3).Infof("HeadObjectHandler %s %s", bucket, object)
|
||||
if _, err := s3a.validateTableBucketObjectPathOrVerify(bucket, object); err != nil {
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -30,10 +30,6 @@ func (s3a *S3ApiServer) GetObjectAclHandler(w http.ResponseWriter, r *http.Reque
|
||||
|
||||
// Check for specific version ID in query parameters
|
||||
versionId := r.URL.Query().Get("versionId")
|
||||
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if versioning is configured for the bucket (Enabled or Suspended)
|
||||
versioningConfigured, err := s3a.isVersioningConfigured(bucket)
|
||||
@@ -93,11 +89,7 @@ func (s3a *S3ApiServer) GetObjectAclHandler(w http.ResponseWriter, r *http.Reque
|
||||
return
|
||||
}
|
||||
|
||||
action := s3_constants.S3_ACTION_GET_OBJECT_ACL
|
||||
if versionId != "" {
|
||||
action = s3_constants.S3_ACTION_GET_OBJECT_VERSION_ACL
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, action, entry.Extended, "GetObjectAclHandler"); errCode != s3err.ErrNone {
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.S3_ACTION_GET_OBJECT_ACL, entry.Extended, "GetObjectAclHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
@@ -150,10 +142,6 @@ func (s3a *S3ApiServer) PutObjectAclHandler(w http.ResponseWriter, r *http.Reque
|
||||
|
||||
// Check for specific version ID in query parameters
|
||||
versionId := r.URL.Query().Get("versionId")
|
||||
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if versioning is configured for the bucket (Enabled or Suspended)
|
||||
versioningConfigured, err := s3a.isVersioningConfigured(bucket)
|
||||
@@ -213,11 +201,7 @@ func (s3a *S3ApiServer) PutObjectAclHandler(w http.ResponseWriter, r *http.Reque
|
||||
return
|
||||
}
|
||||
|
||||
putAction := s3_constants.S3_ACTION_PUT_OBJECT_ACL
|
||||
if versionId != "" {
|
||||
putAction = s3_constants.S3_ACTION_PUT_OBJECT_VERSION_ACL
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, putAction, entry.Extended, "PutObjectAclHandler"); errCode != s3err.ErrNone {
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.S3_ACTION_PUT_OBJECT_ACL, entry.Extended, "PutObjectAclHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -129,10 +129,6 @@ func (s3a *S3ApiServer) GetObjectAttributesHandler(w http.ResponseWriter, r *htt
|
||||
|
||||
// Check for specific version ID
|
||||
versionId := r.URL.Query().Get("versionId")
|
||||
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
entry *filer_pb.Entry
|
||||
@@ -223,24 +219,11 @@ func (s3a *S3ApiServer) GetObjectAttributesHandler(w http.ResponseWriter, r *htt
|
||||
}
|
||||
}
|
||||
|
||||
action := s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES
|
||||
if versionId != "" {
|
||||
action = s3_constants.S3_ACTION_GET_OBJECT_VERSION_ATTRIBUTES
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, action, entry.Extended, "GetObjectAttributesHandler"); errCode != s3err.ErrNone {
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES, entry.Extended, "GetObjectAttributesHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// AWS also asks for the version read grant on a versioned attributes
|
||||
// request: s3:GetObjectVersionAttributes alone is not sufficient.
|
||||
if versionId != "" {
|
||||
if errCode := s3a.checkVersionReadGrant(r, bucket, object, versionId, entry.Extended); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Evaluate conditional headers against the resolved entry (after version resolution)
|
||||
// This ensures conditions are checked against the correct version, not always the latest
|
||||
if s3a.hasConditionalHeaders(r) {
|
||||
|
||||
@@ -900,13 +900,13 @@ func pathToBucketObjectAndVersion(rawPath, decodedPath string) (bucket, object,
|
||||
}
|
||||
|
||||
bucket, object = pathToBucketAndObject(pathForBucket)
|
||||
return bucket, s3_constants.NormalizeObjectKey(object), versionId
|
||||
return bucket, object, versionId
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bucket, object = pathToBucketAndObject(pathForBucket)
|
||||
return bucket, s3_constants.NormalizeObjectKey(object), versionId
|
||||
return bucket, object, versionId
|
||||
}
|
||||
|
||||
type CopyPartResult struct {
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
@@ -376,63 +375,6 @@ func TestCopyObjectPartInlineContent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The handler must route an inline-Content source away from the raw chunk
|
||||
// copy — CopyObjectPartHandler has to send it through the plaintext stream
|
||||
// path or the part lands as zeros.
|
||||
func TestCopyObjectPartHandlerInlineContent(t *testing.T) {
|
||||
volume := startFakeVolumeServer(t)
|
||||
filerImpl := &ambiguousPutFiler{volume: volume, apply: true, entries: map[string]*filer_pb.Entry{}}
|
||||
s3a := newPutTestServer(t, startFakeFiler(t, filerImpl))
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
util_http.InitGlobalHttpClient()
|
||||
|
||||
content := []byte("inline-content")
|
||||
uploadID := s3a.generateUploadID("dst")
|
||||
filerImpl.entries["/buckets/b"] = &filer_pb.Entry{Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}}
|
||||
filerImpl.entries["/buckets/b/src"] = &filer_pb.Entry{
|
||||
Name: "src",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(content))},
|
||||
Content: content,
|
||||
}
|
||||
filerImpl.entries["/buckets/b/.uploads/"+uploadID] = &filer_pb.Entry{
|
||||
Name: uploadID,
|
||||
IsDirectory: true,
|
||||
Extended: map[string][]byte{s3_constants.ExtMultipartObjectKey: []byte("dst")},
|
||||
}
|
||||
|
||||
r := httptest.NewRequest(http.MethodPut, "/b/dst?partNumber=1&uploadId="+uploadID, nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": "b", "object": "dst"})
|
||||
r.Header.Set("X-Amz-Copy-Source", "/b/src")
|
||||
r.Header.Set("x-amz-copy-source-range", "bytes=2-5")
|
||||
w := httptest.NewRecorder()
|
||||
s3a.CopyObjectPartHandler(w, r)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("CopyObjectPartHandler = %d %s, want 200", w.Code, w.Body.String())
|
||||
}
|
||||
wantMd5 := fmt.Sprintf("%x", md5.Sum(content[2:6]))
|
||||
if !strings.Contains(w.Body.String(), wantMd5) {
|
||||
t.Errorf("response %q does not contain copied-range ETag %q", w.Body.String(), wantMd5)
|
||||
}
|
||||
var partEntry *filer_pb.Entry
|
||||
for key, e := range filerImpl.entries {
|
||||
if strings.Contains(key, uploadID) && !e.IsDirectory {
|
||||
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.
|
||||
|
||||
@@ -210,7 +210,7 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
|
||||
// The filer ops below each retry, and a failover walk runs the whole set
|
||||
// once per filer, so the backoff comes out of one allowance held here.
|
||||
r = r.WithContext(withFilerRetryBudget(r.Context(), filerRetryRequestBudget))
|
||||
if _, err := s3a.validateTableBucketObjectPathOrVerify(bucket, object); err != nil {
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
@@ -479,44 +479,29 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
|
||||
deleteErrors = append(deleteErrors, deleteErrorFromCode(validationCode, object.Key, object.VersionId))
|
||||
continue
|
||||
}
|
||||
key := s3_constants.NormalizeObjectKey(object.Key)
|
||||
if key == "" {
|
||||
// A key of only slashes can never name a stored entry; like a
|
||||
// missing key the delete is an idempotent no-op, and a
|
||||
// conditional delete has no target to match.
|
||||
if object.ETag != "" {
|
||||
deleteErrors = append(deleteErrors, deleteErrorFromCode(s3err.ErrNoSuchKey, object.Key, object.VersionId))
|
||||
continue
|
||||
}
|
||||
deletedCount++
|
||||
if !deleteObjects.Quiet {
|
||||
deletedObjects = append(deletedObjects, ObjectIdentifier{Key: object.Key, VersionId: object.VersionId})
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := s3a.validateTableBucketObjectPathOrVerify(bucket, key); err != nil {
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object.Key); err != nil {
|
||||
deleteErrors = append(deleteErrors, deleteErrorFromCode(s3err.ErrAccessDenied, object.Key, object.VersionId))
|
||||
continue
|
||||
}
|
||||
if authErr := s3a.iam.AuthorizeObjectDelete(r, identity, bucket, key, object.VersionId); authErr != s3err.ErrNone {
|
||||
if authErr := s3a.iam.AuthorizeObjectDelete(r, identity, bucket, object.Key, object.VersionId); authErr != s3err.ErrNone {
|
||||
// Defer to the recheck, mirroring the copy-source fallback: a
|
||||
// tag-conditioned Allow may still grant what phase one denied.
|
||||
if authErr != s3err.ErrAccessDenied || s3a.recheckPolicyForKeyWithLookup(r, http.MethodDelete, bucket, key, object.VersionId, string(s3_constants.ACTION_WRITE), "DeleteMultipleObjectsHandler") != s3err.ErrNone {
|
||||
if authErr != s3err.ErrAccessDenied || s3a.recheckPolicyForKeyWithLookup(r, http.MethodDelete, bucket, object.Key, object.VersionId, string(s3_constants.ACTION_WRITE), "DeleteMultipleObjectsHandler") != s3err.ErrNone {
|
||||
deleteErrors = append(deleteErrors, deleteErrorFromCode(authErr, object.Key, object.VersionId))
|
||||
continue
|
||||
}
|
||||
}
|
||||
if errCode := s3a.recheckTagConditionedPolicyWithLookup(objectKeyPolicyRequest(r, http.MethodDelete, bucket, key, object.VersionId), bucket, key, object.VersionId, string(s3_constants.ACTION_WRITE), "DeleteMultipleObjectsHandler"); errCode != s3err.ErrNone {
|
||||
if errCode := s3a.recheckTagConditionedPolicyWithLookup(objectKeyPolicyRequest(r, http.MethodDelete, bucket, object.Key, object.VersionId), bucket, object.Key, object.VersionId, string(s3_constants.ACTION_WRITE), "DeleteMultipleObjectsHandler"); errCode != s3err.ErrNone {
|
||||
deleteErrors = append(deleteErrors, deleteErrorFromCode(errCode, object.Key, object.VersionId))
|
||||
continue
|
||||
}
|
||||
|
||||
var deleteResult deleteMutationResult
|
||||
deleteCode := s3a.withObjectWriteLock(bucket, key, func() s3err.ErrorCode {
|
||||
return s3a.checkDeleteIfMatch(bucket, key, object.VersionId, versioningState, object.ETag, s3err.ErrNoSuchKey)
|
||||
deleteCode := s3a.withObjectWriteLock(bucket, object.Key, func() s3err.ErrorCode {
|
||||
return s3a.checkDeleteIfMatch(bucket, object.Key, object.VersionId, versioningState, object.ETag, s3err.ErrNoSuchKey)
|
||||
}, func() s3err.ErrorCode {
|
||||
if versioningConfigured {
|
||||
result, errCode := s3a.deleteVersionedObject(r, bucket, key, object.VersionId, versioningState)
|
||||
result, errCode := s3a.deleteVersionedObject(r, bucket, object.Key, object.VersionId, versioningState)
|
||||
if errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
@@ -524,18 +509,18 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, key)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, key, "", governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("DeleteMultipleObjectsHandler: object lock check failed for %s/%s: %v", bucket, key, err)
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object.Key)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, object.Key, "", governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("DeleteMultipleObjectsHandler: object lock check failed for %s/%s: %v", bucket, object.Key, err)
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
if strings.HasSuffix(key, "/") {
|
||||
return s3a.deleteDirectoryMarker(r, bucket, key)
|
||||
if strings.HasSuffix(object.Key, "/") {
|
||||
return s3a.deleteDirectoryMarker(r, bucket, object.Key)
|
||||
}
|
||||
|
||||
if err := s3a.deleteUnversionedObjectWithClient(r.Context(), client, bucket, key, false); err != nil {
|
||||
glog.Errorf("DeleteMultipleObjectsHandler: failed to delete %s/%s: %v", bucket, key, err)
|
||||
if err := s3a.deleteUnversionedObjectWithClient(r.Context(), client, bucket, object.Key, false); err != nil {
|
||||
glog.Errorf("DeleteMultipleObjectsHandler: failed to delete %s/%s: %v", bucket, object.Key, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
|
||||
@@ -540,6 +540,18 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
}
|
||||
dirName, entryName, _ := entryUrlEncode(dir, entry.Name, encodingTypeUrl)
|
||||
if entry.IsDirectory {
|
||||
if cursor.emitDirAsCommonPrefix {
|
||||
cursor.emitDirAsCommonPrefix = false
|
||||
dirPrefix := fmt.Sprintf("%s/%s/", dir, entry.Name)[len(bucketPrefix):]
|
||||
commonPrefixes = append(commonPrefixes, PrefixEntry{
|
||||
Prefix: dirPrefix,
|
||||
})
|
||||
cursor.maxKeys--
|
||||
lastEntryWasCommonPrefix = true
|
||||
lastCommonPrefix = dirPrefix
|
||||
lastPrefixNullBackers, lastPrefixConfirmed = nil, true
|
||||
return
|
||||
}
|
||||
if originalPrefix != "" {
|
||||
normalizedPrefix := strings.TrimPrefix(strings.TrimSuffix(originalPrefix, "/"), "/")
|
||||
if normalizedPrefix != "" {
|
||||
@@ -794,6 +806,9 @@ type ListingCursor struct {
|
||||
// resolvePendingNulls settles trailing null objects whose .versions sibling
|
||||
// has not streamed yet before a page is declared full.
|
||||
resolvePendingNulls func() error
|
||||
// emitDirAsCommonPrefix marks the next directory entry passed to the entry
|
||||
// callback for reporting as a CommonPrefix rather than a Contents key.
|
||||
emitDirAsCommonPrefix bool
|
||||
// prefixObjectKeyOnly limits the next prefix-object entry passed to the entry
|
||||
// callback to its plain key; its "<name>/" CommonPrefix is deferred to the
|
||||
// directory's own block position.
|
||||
@@ -1009,8 +1024,10 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
|
||||
}
|
||||
isKeyObject := e.IsDirectoryKeyObject() && !e.IsPrefixObject()
|
||||
if delimiter != "/" || cursor.prefixEndsOnDelimiter {
|
||||
// A trailing-slash prefix (e.g. "logs/") names one directory, so the
|
||||
// recursion below answers whether it exists and what it holds.
|
||||
// A trailing-slash prefix (e.g. "logs/") names one directory and asks
|
||||
// whether it exists, so a real but empty directory must be reported for
|
||||
// that probe.
|
||||
explicitDirProbe := cursor.prefixEndsOnDelimiter
|
||||
if cursor.prefixEndsOnDelimiter {
|
||||
cursor.prefixEndsOnDelimiter = false
|
||||
}
|
||||
@@ -1019,7 +1036,13 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
|
||||
// appear as regular keys in recursive listing mode.
|
||||
eachEntryFn(dir, emitEntry)
|
||||
}
|
||||
subNextMarker, subErr := s3a.doListFilerEntries(ctx, client, listDirectoryRequest{dir: dir + "/" + e.Name, marker: subMarker, delimiter: delimiter, bucket: bucket}, cursor, eachEntryFn)
|
||||
// Recurse into subdirectory to list any children, noting whether the
|
||||
// subtree produced any entries.
|
||||
childEmitted := false
|
||||
subNextMarker, subErr := s3a.doListFilerEntries(ctx, client, listDirectoryRequest{dir: dir + "/" + e.Name, marker: subMarker, delimiter: delimiter, bucket: bucket}, cursor, func(d string, ent *filer_pb.Entry) {
|
||||
childEmitted = true
|
||||
eachEntryFn(d, ent)
|
||||
})
|
||||
if subErr != nil {
|
||||
return fmt.Errorf("doListFilerEntries2: %w", subErr)
|
||||
}
|
||||
@@ -1029,10 +1052,26 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
|
||||
// keep a resume position that re-enters it.
|
||||
cursor.isTruncated = true
|
||||
}
|
||||
// An empty directory gets no marker under its own "<dir>/" prefix:
|
||||
// that listing enumerates children, where S3 returns nothing for an
|
||||
// empty prefix, and a fake entry is read back as a real object by
|
||||
// clients that enumerate locks or similar.
|
||||
// A real but empty directory (created out of band via mount, mkdir or
|
||||
// the filer API, so it carries no MIME) is otherwise invisible to S3
|
||||
// clients that detect directories by listing it under its own "<dir>/"
|
||||
// prefix. Answer that explicit probe so tools like hadoop-aws can find
|
||||
// the directory: a delimited listing reports it as a CommonPrefix --
|
||||
// a real key in Contents would look like an object a client can read --
|
||||
// while a recursive listing keeps the directory marker key it used.
|
||||
// Plain listings are left untouched, so empty directories left behind
|
||||
// by deleted objects are not shown as keys.
|
||||
// A directory that still holds version history no longer names anything,
|
||||
// so it gets no marker either.
|
||||
if explicitDirProbe && !isKeyObject && !childEmitted && !cursor.isTruncated && e.Attributes != nil &&
|
||||
!s3a.dirHoldsOnlyHiddenEntries(ctx, client, bucket, dir+"/"+e.Name, cursor) {
|
||||
if delimiter == "/" {
|
||||
cursor.emitDirAsCommonPrefix = true
|
||||
} else {
|
||||
emitEntry.Attributes.Mime = s3_constants.FolderMimeType
|
||||
}
|
||||
eachEntryFn(dir, emitEntry)
|
||||
}
|
||||
// println("doListFilerEntries2 dir", dir+"/"+e.Name, "subNextMarker", subNextMarker)
|
||||
if cursor.isTruncated || matchedPrefixDir {
|
||||
stopped = true
|
||||
|
||||
@@ -65,11 +65,12 @@ func TestDirectoryListedAsCommonPrefix(t *testing.T) {
|
||||
assert.Empty(t, seenFiles, "No files should be seen, only the directory")
|
||||
}
|
||||
|
||||
// TestEmptyDirectoryNotListedUnderOwnPrefix covers the explicit "<dir>/" probe
|
||||
// on a real but empty directory (created via mount, mkdir or the filer API, so
|
||||
// it has no MIME): it is listed under its own prefix in neither delimited nor
|
||||
// recursive mode, matching S3 where an empty prefix has no key to return.
|
||||
func TestEmptyDirectoryNotListedUnderOwnPrefix(t *testing.T) {
|
||||
// TestEmptyDirectorySurfacedAsMarker reproduces the hadoop-aws / Spark case where a
|
||||
// real but empty directory (created via mount, mkdir or the filer API, so it has no
|
||||
// MIME) must be visible to S3 clients that detect directories by listing under the
|
||||
// "<dir>/" prefix. Under a delimiter it is reported as a CommonPrefix, which the
|
||||
// probe accepts, instead of a key a client might try to read.
|
||||
func TestEmptyDirectorySurfacedAsMarker(t *testing.T) {
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{BucketsPath: "/buckets"},
|
||||
}
|
||||
@@ -86,15 +87,20 @@ func TestEmptyDirectoryNotListedUnderOwnPrefix(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
for _, delimiter := range []string{"/", ""} {
|
||||
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
|
||||
var seen []*filer_pb.Entry
|
||||
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test", prefix: "logs", delimiter: delimiter, bucket: "test"}, cursor,
|
||||
func(dir string, entry *filer_pb.Entry) {
|
||||
seen = append(seen, entry)
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, seen, "an empty directory reports nothing under its own prefix (delimiter %q)", delimiter)
|
||||
// Mirrors the getFileStatus probe: prefix "logs/" with delimiter "/".
|
||||
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
|
||||
var seen []*filer_pb.Entry
|
||||
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test", prefix: "logs", delimiter: "/", bucket: "test"}, cursor,
|
||||
func(dir string, entry *filer_pb.Entry) {
|
||||
seen = append(seen, entry)
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, seen, 1, "empty directory must be surfaced under the logs/ prefix") {
|
||||
assert.True(t, cursor.emitDirAsCommonPrefix,
|
||||
"a delimited probe reports the empty directory as a common prefix")
|
||||
assert.Empty(t, seen[0].Attributes.Mime,
|
||||
"the entry must not be dressed as a directory key object")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,10 +185,10 @@ func TestEmptyDirectoryHiddenInFlatListing(t *testing.T) {
|
||||
assert.Equal(t, []string{"foo"}, seen, "flat listing must hide the empty directory and return only real objects")
|
||||
}
|
||||
|
||||
// A trailing-slash delimited listing of an empty directory enumerates its
|
||||
// children, so it returns nothing: the directory is neither a readable Contents
|
||||
// key nor a CommonPrefix of its own.
|
||||
func TestEmptyDirectoryHiddenInDelimitedSelfListing(t *testing.T) {
|
||||
// A trailing-slash delimited listing of an empty directory reports the
|
||||
// directory as a CommonPrefix, not as a Contents key: clients that treat
|
||||
// every returned key as an object (e.g. lock listings) skip prefixes.
|
||||
func TestEmptyDirectoryListedAsCommonPrefix(t *testing.T) {
|
||||
filer := &fakeBucketDeleteFiler{entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/test": {
|
||||
{Name: "locks", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
@@ -202,5 +208,6 @@ func TestEmptyDirectoryHiddenInDelimitedSelfListing(t *testing.T) {
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, response.Contents, "an empty directory is not a readable key")
|
||||
assert.Empty(t, response.CommonPrefixes, "an empty directory has no prefixes to fold into")
|
||||
require.Len(t, response.CommonPrefixes, 1)
|
||||
assert.Equal(t, "locks/", response.CommonPrefixes[0].Prefix)
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -81,9 +80,9 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
|
||||
}
|
||||
|
||||
// Verify policy signature.
|
||||
identity, errCode := s3a.iam.doesPolicySignatureMatch(r.Context(), formValues)
|
||||
identity, errCode := s3a.iam.doesPolicySignatureMatch(formValues)
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, refineDenialForBucketName(r, identity, errCode))
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
if identity != nil {
|
||||
@@ -141,7 +140,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
|
||||
|
||||
// Authorize the object like the PUT path; the coarse Write check above does not consult the bucket policy.
|
||||
if errCode := s3a.iam.AuthorizeObjectWrite(r, identity, bucket, object); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, refineDenialForBucketName(r, identity, errCode))
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -363,25 +362,10 @@ func getRedirectPostRawQuery(bucket, key, etag string) string {
|
||||
}
|
||||
|
||||
// Check to see if Policy is signed correctly, returning the signing identity.
|
||||
// The verified form's access key is recorded in ctx's identity holder. The
|
||||
// identity's Write permission on the bucket is checked only once the signature
|
||||
// verifies, as on the header-signed path, so a form that fails verification
|
||||
// learns nothing about the key's permissions. A verified identity that may not
|
||||
// write is returned with ErrAccessDenied.
|
||||
func (iam *IdentityAccessManagement) doesPolicySignatureMatch(ctx context.Context, formValues http.Header) (*Identity, s3err.ErrorCode) {
|
||||
var identity *Identity
|
||||
var errCode s3err.ErrorCode
|
||||
func (iam *IdentityAccessManagement) doesPolicySignatureMatch(formValues http.Header) (*Identity, s3err.ErrorCode) {
|
||||
// For SignV2 - Signature field will be valid
|
||||
if _, ok := formValues["Signature"]; ok {
|
||||
identity, errCode = iam.doesPolicySignatureV2Match(ctx, formValues)
|
||||
} else {
|
||||
identity, errCode = iam.doesPolicySignatureV4Match(ctx, formValues)
|
||||
return iam.doesPolicySignatureV2Match(formValues)
|
||||
}
|
||||
if errCode != s3err.ErrNone {
|
||||
return nil, errCode
|
||||
}
|
||||
if !identity.CanDo(s3_constants.ACTION_WRITE, formValues.Get("bucket"), "") {
|
||||
return identity, s3err.ErrAccessDenied
|
||||
}
|
||||
return identity, s3err.ErrNone
|
||||
return iam.doesPolicySignatureV4Match(formValues)
|
||||
}
|
||||
@@ -112,7 +112,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrKeyTooLongError)
|
||||
return
|
||||
}
|
||||
if isVerify, err := s3a.validateTableBucketObjectPathOrVerify(bucket, object); err != nil || (isVerify && !volumeVerifyPutAllowed(r, object)) {
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
@@ -991,11 +991,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
|
||||
}
|
||||
glog.V(3).Infof("putToFiler: Calling CreateEntry for %s", filePath)
|
||||
err := filer_pb.CreateEntry(context.Background(), client, req)
|
||||
// A verification key in a table bucket never becomes a prefix
|
||||
// object: the directory it meets is a namespace, created after the
|
||||
// handler looked.
|
||||
if errors.Is(err, filer_pb.ErrExistingIsDirectory) && !isReservedDirectoryName(entry.Name) &&
|
||||
!(isVolumeVerifyKey(object) && s3a.isTableBucket(bucket)) {
|
||||
if errors.Is(err, filer_pb.ErrExistingIsDirectory) && !isReservedDirectoryName(entry.Name) {
|
||||
// Other keys are nested under this one. S3 keys are flat, so the key is
|
||||
// stored on the directory they live under rather than refused.
|
||||
entry.MarkPrefixObject()
|
||||
|
||||
@@ -29,10 +29,6 @@ func (s3a *S3ApiServer) GetObjectTaggingHandler(w http.ResponseWriter, r *http.R
|
||||
|
||||
// Check for specific version ID in query parameters
|
||||
versionId := r.URL.Query().Get("versionId")
|
||||
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if versioning is configured for the bucket (Enabled or Suspended)
|
||||
versioningConfigured, err := s3a.isVersioningConfigured(bucket)
|
||||
@@ -91,11 +87,7 @@ func (s3a *S3ApiServer) GetObjectTaggingHandler(w http.ResponseWriter, r *http.R
|
||||
}
|
||||
}
|
||||
|
||||
action := s3_constants.S3_ACTION_GET_OBJECT_TAGGING
|
||||
if versionId != "" {
|
||||
action = s3_constants.S3_ACTION_GET_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, action, entry.Extended, "GetObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.S3_ACTION_GET_OBJECT_TAGGING, entry.Extended, "GetObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
@@ -148,10 +140,6 @@ func (s3a *S3ApiServer) PutObjectTaggingHandler(w http.ResponseWriter, r *http.R
|
||||
|
||||
// Check for specific version ID in query parameters
|
||||
versionId := r.URL.Query().Get("versionId")
|
||||
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if versioning is configured for the bucket (Enabled or Suspended)
|
||||
versioningConfigured, err := s3a.isVersioningConfigured(bucket)
|
||||
@@ -197,11 +185,7 @@ func (s3a *S3ApiServer) PutObjectTaggingHandler(w http.ResponseWriter, r *http.R
|
||||
target := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), object))
|
||||
dir, name := target.DirAndName()
|
||||
|
||||
putAction := s3_constants.S3_ACTION_PUT_OBJECT_TAGGING
|
||||
if versionId != "" {
|
||||
putAction = s3_constants.S3_ACTION_PUT_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if errCode := s3a.recheckTagConditionedPolicyWithLookup(r, bucket, object, versionId, putAction, "PutObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
if errCode := s3a.recheckTagConditionedPolicyWithLookup(r, bucket, object, versionId, s3_constants.S3_ACTION_PUT_OBJECT_TAGGING, "PutObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
@@ -222,11 +206,7 @@ func (s3a *S3ApiServer) PutObjectTaggingHandler(w http.ResponseWriter, r *http.R
|
||||
return
|
||||
}
|
||||
|
||||
putAction := s3_constants.S3_ACTION_PUT_OBJECT_TAGGING
|
||||
if versionId != "" {
|
||||
putAction = s3_constants.S3_ACTION_PUT_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, putAction, entry.Extended, "PutObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.S3_ACTION_PUT_OBJECT_TAGGING, entry.Extended, "PutObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
@@ -288,10 +268,6 @@ func (s3a *S3ApiServer) DeleteObjectTaggingHandler(w http.ResponseWriter, r *htt
|
||||
|
||||
// Check for specific version ID in query parameters
|
||||
versionId := r.URL.Query().Get("versionId")
|
||||
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if versioning is configured for the bucket (Enabled or Suspended)
|
||||
versioningConfigured, err := s3a.isVersioningConfigured(bucket)
|
||||
@@ -337,11 +313,7 @@ func (s3a *S3ApiServer) DeleteObjectTaggingHandler(w http.ResponseWriter, r *htt
|
||||
target := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), object))
|
||||
dir, name := target.DirAndName()
|
||||
|
||||
deleteAction := s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING
|
||||
if versionId != "" {
|
||||
deleteAction = s3_constants.S3_ACTION_DELETE_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if errCode := s3a.recheckTagConditionedPolicyWithLookup(r, bucket, object, versionId, deleteAction, "DeleteObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
if errCode := s3a.recheckTagConditionedPolicyWithLookup(r, bucket, object, versionId, s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING, "DeleteObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
@@ -363,11 +335,7 @@ func (s3a *S3ApiServer) DeleteObjectTaggingHandler(w http.ResponseWriter, r *htt
|
||||
return
|
||||
}
|
||||
|
||||
deleteAction := s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING
|
||||
if versionId != "" {
|
||||
deleteAction = s3_constants.S3_ACTION_DELETE_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, deleteAction, entry.Extended, "DeleteObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING, entry.Extended, "DeleteObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -78,14 +78,6 @@ type S3ApiServerOption struct {
|
||||
// AllowUntrustedRemoteEndpoints lets a read of a remote-only object dial a
|
||||
// mounted endpoint that resolves to a loopback / private / metadata host.
|
||||
AllowUntrustedRemoteEndpoints bool
|
||||
// AllowBackslashInKey keeps '\' a literal object-key character instead of
|
||||
// normalizing it to '/', matching AWS S3 where the two are distinct keys.
|
||||
AllowBackslashInKey bool
|
||||
// IamSelfServiceRequiresGrant makes managing one's own access keys
|
||||
// (CreateAccessKey, DeleteAccessKey, UpdateAccessKey, ListAccessKeys,
|
||||
// GetUser) need an explicit iam: grant instead of being allowed to every
|
||||
// authenticated identity.
|
||||
IamSelfServiceRequiresGrant bool
|
||||
}
|
||||
|
||||
// s3ChunkCacheChunkSizeMB is the assumed chunk size (in MiB) used to convert
|
||||
@@ -540,10 +532,6 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
// pointer-to-missing-file states without waiting for a client GET.
|
||||
s3ApiServer.versionsReconcilerStop = s3ApiServer.startVersioningReconciler()
|
||||
|
||||
// Publish the key mode only once the server is fully constructed so a
|
||||
// failed construction cannot flip the mode of a running server.
|
||||
SetAllowBackslashInObjectKey(option.AllowBackslashInKey)
|
||||
|
||||
return s3ApiServer, nil
|
||||
}
|
||||
|
||||
@@ -673,10 +661,7 @@ func (s3a *S3ApiServer) checkPolicyWithEntry(r *http.Request, bucket, object, ac
|
||||
// Returns s3err.ErrNone if allowed, or an error code if denied or on error.
|
||||
func (s3a *S3ApiServer) recheckPolicyWithObjectEntry(r *http.Request, bucket, object, action string, objectEntry map[string][]byte, handlerName string) s3err.ErrorCode {
|
||||
if isAnonymousObjectRead(r) {
|
||||
// Refined like writeAnonymousAwareNotFound's masked miss, so a denied
|
||||
// existing key and a missing key answer alike on a malformed name.
|
||||
identity, _ := GetIdentityFromContext(r).(*Identity)
|
||||
return refineDenialForBucketName(r, identity, s3a.authorizeAnonymousObjectRead(r, bucket, object, objectEntry))
|
||||
return s3a.authorizeAnonymousObjectRead(r, bucket, object, objectEntry)
|
||||
}
|
||||
identityRaw := GetIdentityFromContext(r)
|
||||
var identity *Identity
|
||||
@@ -693,21 +678,6 @@ func (s3a *S3ApiServer) recheckPolicyWithObjectEntry(r *http.Request, bucket, ob
|
||||
return errCode
|
||||
}
|
||||
|
||||
// checkVersionReadGrant enforces the version read grant AWS requires alongside
|
||||
// a version-scoped action such as s3:GetObjectVersionAttributes. The check runs
|
||||
// on a request shaped like a plain versioned GET so the s3:GetObjectVersion
|
||||
// action resolves from the request instead of the caller's subresource, and a
|
||||
// legacy Read grant still applies.
|
||||
func (s3a *S3ApiServer) checkVersionReadGrant(r *http.Request, bucket, object, versionId string, objectEntry map[string][]byte) s3err.ErrorCode {
|
||||
versionReadReq := objectKeyPolicyRequest(r, http.MethodGet, bucket, object, versionId)
|
||||
if identity, ok := GetIdentityFromContext(r).(*Identity); ok && identity != nil {
|
||||
if errCode := s3a.iam.VerifyActionPermission(versionReadReq, identity, ACTION_READ, bucket, object); errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
}
|
||||
return s3a.recheckPolicyWithObjectEntry(versionReadReq, bucket, object, ACTION_READ, objectEntry, "checkVersionReadGrant")
|
||||
}
|
||||
|
||||
// recheckCopySourcePolicy repeats the source object's policy check once its
|
||||
// entry is fetched, so conditions on the object's existing tags apply to a
|
||||
// CopyObject / UploadPartCopy / RenameObject source the same way they do to a
|
||||
@@ -921,9 +891,6 @@ func (s3a *S3ApiServer) UnifiedPostHandler(w http.ResponseWriter, r *http.Reques
|
||||
func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
|
||||
// runs before subrouter matching so Queries() matchers see the fixed query
|
||||
router.Use(util_http.EscapeSemicolonsInQuery)
|
||||
// a request naming two subresources routes one way and authorizes another;
|
||||
// reject it rather than guess
|
||||
router.Use(rejectAmbiguousSubresource)
|
||||
// API Router
|
||||
apiRouter := router.PathPrefix("/").Subrouter()
|
||||
apiRouter.Use(request_id.Middleware)
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// rejectAmbiguousSubresource applies the same one-operation-per-request rule
|
||||
// validateRequestPath enforces inside bucket routes to the routes outside them,
|
||||
// so the check runs once for every request the router serves.
|
||||
func rejectAmbiguousSubresource(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if hasAmbiguousSubresource(r.URL.Query()) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user