mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d60f5201f9 | ||
|
|
4e058c2bce | ||
|
|
849d7949a3 | ||
|
|
1690bb2a03 | ||
|
|
59228cf809 | ||
|
|
79164c8eef | ||
|
|
b122308bf4 | ||
|
|
e96190d128 | ||
|
|
7b0b64db65 | ||
|
|
1c0e24f06a | ||
|
|
12f283357f | ||
|
|
9af1b212d3 | ||
|
|
9d6a699b94 | ||
|
|
6483583491 | ||
|
|
bc1d458fe6 | ||
|
|
1d3454ca5c | ||
|
|
6554ab7928 | ||
|
|
f8973b3ed6 | ||
|
|
6141222ab0 | ||
|
|
95560076e6 | ||
|
|
22ebe9feb0 | ||
|
|
4ded97a321 | ||
|
|
d951a8df5a | ||
|
|
2417ba0354 | ||
|
|
a769c938ec | ||
|
|
6d95a5592a | ||
|
|
0a91b57f16 | ||
|
|
e1d5e3899f | ||
|
|
3ee147dc4d | ||
|
|
66d9b89cd2 | ||
|
|
57bb7b2f39 |
No files matched your search
@@ -57,12 +57,12 @@ jobs:
|
||||
echo "FUSE device: $(ls -la /dev/fuse 2>&1 || echo '/dev/fuse not found')"
|
||||
|
||||
- name: Start SeaweedFS
|
||||
timeout-minutes: 10
|
||||
timeout-minutes: 15
|
||||
run: |
|
||||
# Enable Docker buildkit for better caching
|
||||
export DOCKER_BUILDKIT=1
|
||||
export COMPOSE_DOCKER_CLI_BUILD=1
|
||||
|
||||
|
||||
# Build with retry logic
|
||||
for i in {1..3}; do
|
||||
echo "Build attempt $i/3"
|
||||
@@ -77,10 +77,18 @@ jobs:
|
||||
sleep 30
|
||||
fi
|
||||
done
|
||||
|
||||
|
||||
# Start services with wait
|
||||
docker compose -f ./compose/e2e-mount.yml up --wait
|
||||
|
||||
- name: Rotate buildx cache
|
||||
if: always()
|
||||
run: |
|
||||
# Without this, --cache-to writes to .buildx-cache-new but actions/cache only
|
||||
# uploads .buildx-cache, so layers (notably the slow apt RUN) never persist.
|
||||
rm -rf /tmp/.buildx-cache
|
||||
if [ -d /tmp/.buildx-cache-new ]; then mv /tmp/.buildx-cache-new /tmp/.buildx-cache; fi
|
||||
|
||||
- name: Run FIO 4k
|
||||
timeout-minutes: 15
|
||||
run: |
|
||||
|
||||
@@ -662,6 +662,77 @@ jobs:
|
||||
path: test/s3tables/lakekeeper/test-output.log
|
||||
retention-days: 3
|
||||
|
||||
unity-catalog-integration-tests:
|
||||
name: Unity Catalog Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
id: go
|
||||
|
||||
- name: Set up Docker
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Pre-pull Unity Catalog image
|
||||
run: docker pull unitycatalog/unitycatalog:v0.4.0
|
||||
|
||||
- name: Pre-pull Python image for delta-rs writer
|
||||
run: docker pull python:3.11-slim
|
||||
|
||||
- name: Run go mod tidy
|
||||
run: go mod tidy
|
||||
|
||||
- name: Install SeaweedFS
|
||||
run: |
|
||||
go install -buildvcs=false ./weed
|
||||
|
||||
- name: Run Unity Catalog Integration Tests
|
||||
timeout-minutes: 25
|
||||
working-directory: test/s3tables/unity_catalog
|
||||
run: |
|
||||
set -x
|
||||
set -o pipefail
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
docker info
|
||||
echo "=== Starting Unity Catalog Tests ==="
|
||||
|
||||
go test -v -timeout 20m . 2>&1 | tee test-output.log || {
|
||||
echo "Unity Catalog integration tests failed"
|
||||
exit 1
|
||||
}
|
||||
|
||||
- name: Show test output on failure
|
||||
if: failure()
|
||||
working-directory: test/s3tables/unity_catalog
|
||||
run: |
|
||||
echo "=== Test Output ==="
|
||||
if [ -f test-output.log ]; then
|
||||
tail -200 test-output.log
|
||||
fi
|
||||
|
||||
echo "=== Process information ==="
|
||||
ps aux | grep -E "(weed|test|docker|unitycatalog)" || true
|
||||
echo "=== Unity Catalog containers ==="
|
||||
docker ps -a --filter "name=seaweed-unity-catalog" || true
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: unity-catalog-integration-test-logs
|
||||
path: test/s3tables/unity_catalog/test-output.log
|
||||
retention-days: 3
|
||||
|
||||
s3-tables-build-verification:
|
||||
name: S3 Tables Build Verification
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
@@ -2,13 +2,15 @@ FROM ubuntu:22.04
|
||||
|
||||
LABEL author="Chris Lu"
|
||||
|
||||
# Use faster mirrors and optimize package installation
|
||||
# Use Azure's Ubuntu mirror — much faster than archive.ubuntu.com from GitHub-hosted runners,
|
||||
# which have been hanging long enough on Ign:/retry to trip the 10-min step timeout.
|
||||
# Note: This e2e test image intentionally runs as root for simplicity and compatibility.
|
||||
# Production images (Dockerfile.go_build) use proper user isolation with su-exec.
|
||||
# For testing purposes, running as root avoids permission complexities and dependency
|
||||
# on Alpine-specific tools like su-exec (not available in Ubuntu repos).
|
||||
RUN apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 update && \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 install -y \
|
||||
RUN sed -i 's|http://archive.ubuntu.com/ubuntu|http://azure.archive.ubuntu.com/ubuntu|g; s|http://security.ubuntu.com/ubuntu|http://azure.archive.ubuntu.com/ubuntu|g' /etc/apt/sources.list && \
|
||||
apt-get -o Acquire::http::Timeout=15 update && \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::http::Timeout=15 install -y \
|
||||
--no-install-recommends \
|
||||
--no-install-suggests \
|
||||
curl \
|
||||
|
||||
@@ -113,7 +113,7 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/kms v1.26.0
|
||||
cloud.google.com/go/kms v1.30.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0
|
||||
github.com/Jille/raft-grpc-transport v1.6.1
|
||||
github.com/ThreeDotsLabs/watermill v1.5.1
|
||||
|
||||
@@ -298,8 +298,8 @@ cloud.google.com/go/kms v1.4.0/go.mod h1:fajBHndQ+6ubNw6Ss2sSd+SWvjL26RNo/dr7uxs
|
||||
cloud.google.com/go/kms v1.5.0/go.mod h1:QJS2YY0eJGBg3mnDfuaCyLauWwBJiHRboYxJ++1xJNg=
|
||||
cloud.google.com/go/kms v1.6.0/go.mod h1:Jjy850yySiasBUDi6KFUwUv2n1+o7QZFyuUJg6OgjA0=
|
||||
cloud.google.com/go/kms v1.9.0/go.mod h1:qb1tPTgfF9RQP8e1wq4cLFErVuTJv7UsSC915J8dh3w=
|
||||
cloud.google.com/go/kms v1.26.0 h1:cK9mN2cf+9V63D3H1f6koxTatWy39aTI/hCjz1I+adU=
|
||||
cloud.google.com/go/kms v1.26.0/go.mod h1:pHKOdFJm63hxBsiPkYtowZPltu9dW0MWvBa6IA4HM58=
|
||||
cloud.google.com/go/kms v1.30.0 h1:TSEZopy/OXojbVCQS9Rrx0jFqdKWvO31+N8ncXbxG/s=
|
||||
cloud.google.com/go/kms v1.30.0/go.mod h1:YIyXZym11R5uovJJt4oN5eUL3oPmirF3yKeIh6QAf4U=
|
||||
cloud.google.com/go/language v1.4.0/go.mod h1:F9dRpNFQmJbkaop6g0JhSBXCNlO90e1KWx5iDdxbWic=
|
||||
cloud.google.com/go/language v1.6.0/go.mod h1:6dJ8t3B+lUYfStgls25GusK04NLh3eDLQnWM3mdEbhI=
|
||||
cloud.google.com/go/language v1.7.0/go.mod h1:DJ6dYN/W+SQOjF8e1hLQXMF21AkH2w9wiPzPCJa2MIE=
|
||||
|
||||
@@ -247,6 +247,9 @@ message VolumeUnmountResponse {
|
||||
message VolumeDeleteRequest {
|
||||
uint32 volume_id = 1;
|
||||
bool only_empty = 2;
|
||||
// when true, do not remove the cloud-tier object backing the volume.
|
||||
// used for moves where another server is taking over the same .vif.
|
||||
bool keep_remote_data = 3;
|
||||
}
|
||||
message VolumeDeleteResponse {
|
||||
}
|
||||
@@ -637,6 +640,7 @@ message FetchAndWriteNeedleRequest {
|
||||
}
|
||||
repeated Replica replicas = 6;
|
||||
string auth = 7;
|
||||
int32 download_concurrency = 8; // multipart download concurrency if supported by the remote storage client; for S3, 0 = default (5)
|
||||
// remote conf
|
||||
remote_pb.RemoteConf remote_conf = 15;
|
||||
remote_pb.RemoteStorageLocation remote_location = 16;
|
||||
|
||||
@@ -145,6 +145,37 @@ pub struct VolumeGrpcService {
|
||||
}
|
||||
|
||||
impl VolumeGrpcService {
|
||||
/// Verifies the gRPC caller is allowed to invoke a destructive admin
|
||||
/// operation. Mirrors the Go side's checkGrpcAdminAuth: an empty
|
||||
/// whitelist accepts everyone (insecure-by-default for tests and
|
||||
/// upgrades), a populated whitelist accepts only matching peer IPs.
|
||||
///
|
||||
/// `remote_addr()` on a real gRPC connection always yields the peer's
|
||||
/// SocketAddr; if it is somehow None we deny, matching "if we don't
|
||||
/// know who the caller is, refuse."
|
||||
fn check_grpc_admin_auth<T>(&self, request: &Request<T>) -> Result<(), Status> {
|
||||
let remote = match request.remote_addr() {
|
||||
Some(addr) => addr,
|
||||
None => {
|
||||
tracing::warn!("gRPC admin auth failed: no peer info");
|
||||
return Err(Status::permission_denied("no peer info"));
|
||||
}
|
||||
};
|
||||
let host = remote.ip().to_string();
|
||||
let guard = self.state.guard.read().unwrap();
|
||||
if !guard.check_whitelist(&host) {
|
||||
tracing::warn!(
|
||||
"gRPC admin auth failed: {} is not whitelisted (remote: {})",
|
||||
host,
|
||||
remote,
|
||||
);
|
||||
return Err(Status::permission_denied(format!(
|
||||
"not authorized: {host}"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn notify_master_volume_readonly(
|
||||
&self,
|
||||
info: &MasterVolumeInfo,
|
||||
@@ -459,6 +490,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VacuumVolumeCompactRequest>,
|
||||
) -> Result<Response<Self::VacuumVolumeCompactStream>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -518,6 +550,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VacuumVolumeCommitRequest>,
|
||||
) -> Result<Response<volume_server_pb::VacuumVolumeCommitResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let vid = VolumeId(request.into_inner().volume_id);
|
||||
|
||||
@@ -553,6 +586,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VacuumVolumeCleanupRequest>,
|
||||
) -> Result<Response<volume_server_pb::VacuumVolumeCleanupResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let vid = VolumeId(request.into_inner().volume_id);
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
@@ -568,6 +602,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::DeleteCollectionRequest>,
|
||||
) -> Result<Response<volume_server_pb::DeleteCollectionResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let collection = &request.into_inner().collection;
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
store
|
||||
@@ -580,6 +615,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::AllocateVolumeRequest>,
|
||||
) -> Result<Response<volume_server_pb::AllocateVolumeResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -728,6 +764,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeMountRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeMountResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
@@ -744,6 +781,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeUnmountRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeUnmountResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let vid = VolumeId(request.into_inner().volume_id);
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
// Go returns nil when volume is not found (idempotent unmount)
|
||||
@@ -757,6 +795,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeDeleteRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeDeleteResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -770,7 +809,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
}
|
||||
}
|
||||
store
|
||||
.delete_volume(vid, req.only_empty)
|
||||
.delete_volume(vid, req.only_empty, req.keep_remote_data)
|
||||
.map_err(|e| Status::internal(e.to_string()))?;
|
||||
self.state.volume_state_notify.notify_one();
|
||||
Ok(Response::new(volume_server_pb::VolumeDeleteResponse {}))
|
||||
@@ -780,6 +819,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeMarkReadonlyRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeMarkReadonlyResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
// Go: volume lookup (L239-241) happens before maintenance check (L166 in makeVolumeReadonly)
|
||||
@@ -799,6 +839,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeMarkWritableRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeMarkWritableResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
let info = {
|
||||
@@ -848,6 +889,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeConfigureRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeConfigureResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -1001,7 +1043,10 @@ impl VolumeServer for VolumeGrpcService {
|
||||
if store.find_volume(vid).is_some() {
|
||||
drop(store);
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
store.delete_volume(vid, false).map_err(|e| {
|
||||
// keep remote data: the inbound copy carries a .vif that may
|
||||
// point at the same cloud-tier object the existing volume
|
||||
// references.
|
||||
store.delete_volume(vid, false, true).map_err(|e| {
|
||||
Status::internal(format!("failed to delete existing volume {}: {}", vid, e))
|
||||
})?;
|
||||
self.state.volume_state_notify.notify_one();
|
||||
@@ -2542,6 +2587,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeEcShardsDeleteRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsDeleteResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -3240,8 +3286,9 @@ impl VolumeServer for VolumeGrpcService {
|
||||
|
||||
async fn volume_server_leave(
|
||||
&self,
|
||||
_request: Request<volume_server_pb::VolumeServerLeaveRequest>,
|
||||
request: Request<volume_server_pb::VolumeServerLeaveRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeServerLeaveResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
*self.state.is_stopping.write().unwrap() = true;
|
||||
self.state.is_heartbeating.store(false, Ordering::Relaxed);
|
||||
// Wake heartbeat loop to send deregistration.
|
||||
@@ -3391,6 +3438,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::ScrubVolumeRequest>,
|
||||
) -> Result<Response<volume_server_pb::ScrubVolumeResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
|
||||
// Validate mode
|
||||
|
||||
@@ -860,7 +860,7 @@ fn build_heartbeat_with_ec_status(
|
||||
}
|
||||
|
||||
for vid in delete_vids {
|
||||
let _ = loc.delete_volume(vid, false);
|
||||
let _ = loc.delete_volume(vid, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -386,13 +386,20 @@ impl DiskLocation {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove, close, and delete all files for a volume.
|
||||
pub fn delete_volume(&mut self, vid: VolumeId, only_empty: bool) -> Result<(), VolumeError> {
|
||||
/// Remove, close, and delete all files for a volume. When keep_remote_data
|
||||
/// is true the cloud-tier object backing the volume is left intact — used
|
||||
/// by moves where another server is taking over the same .vif.
|
||||
pub fn delete_volume(
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
only_empty: bool,
|
||||
keep_remote_data: bool,
|
||||
) -> Result<(), VolumeError> {
|
||||
if let Some(mut v) = self.volumes.remove(&vid) {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&v.collection, "volume"])
|
||||
.dec();
|
||||
v.destroy(only_empty)?;
|
||||
v.destroy(only_empty, keep_remote_data)?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(VolumeError::NotFound)
|
||||
@@ -413,7 +420,7 @@ impl DiskLocation {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&v.collection, "volume"])
|
||||
.dec();
|
||||
if let Err(e) = v.destroy(false) {
|
||||
if let Err(e) = v.destroy(false, false) {
|
||||
warn!(volume_id = vid.0, error = %e, "delete collection: failed to destroy volume");
|
||||
}
|
||||
}
|
||||
@@ -1157,7 +1164,7 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(loc.volumes_len(), 2);
|
||||
|
||||
loc.delete_volume(VolumeId(1), false).unwrap();
|
||||
loc.delete_volume(VolumeId(1), false, false).unwrap();
|
||||
assert_eq!(loc.volumes_len(), 1);
|
||||
assert!(loc.find_volume(VolumeId(1)).is_none());
|
||||
}
|
||||
|
||||
@@ -307,11 +307,18 @@ impl Store {
|
||||
)
|
||||
}
|
||||
|
||||
/// Delete a volume from any location.
|
||||
pub fn delete_volume(&mut self, vid: VolumeId, only_empty: bool) -> Result<(), VolumeError> {
|
||||
/// Delete a volume from any location. When keep_remote_data is true the
|
||||
/// cloud-tier object backing the volume is left intact — used by moves
|
||||
/// where another server is taking over the same .vif.
|
||||
pub fn delete_volume(
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
only_empty: bool,
|
||||
keep_remote_data: bool,
|
||||
) -> Result<(), VolumeError> {
|
||||
for loc in &mut self.locations {
|
||||
if loc.find_volume(vid).is_some() {
|
||||
return loc.delete_volume(vid, only_empty);
|
||||
return loc.delete_volume(vid, only_empty, keep_remote_data);
|
||||
}
|
||||
}
|
||||
Err(VolumeError::NotFound)
|
||||
|
||||
@@ -3081,7 +3081,10 @@ impl Volume {
|
||||
}
|
||||
|
||||
/// Remove all volume files from disk.
|
||||
pub fn destroy(&mut self, only_empty: bool) -> Result<(), VolumeError> {
|
||||
/// Destroy removes everything related to this volume. When keep_remote_data
|
||||
/// is true the cloud-tier object backing the volume is left intact — used
|
||||
/// by moves where another server is taking over the same .vif.
|
||||
pub fn destroy(&mut self, only_empty: bool, keep_remote_data: bool) -> Result<(), VolumeError> {
|
||||
if only_empty && self.file_count() > 0 {
|
||||
return Err(VolumeError::NotEmpty);
|
||||
}
|
||||
@@ -3093,7 +3096,11 @@ impl Volume {
|
||||
}
|
||||
|
||||
let (storage_name, storage_key) = self.remote_storage_name_key();
|
||||
if self.has_remote_file && !storage_name.is_empty() && !storage_key.is_empty() {
|
||||
if !keep_remote_data
|
||||
&& self.has_remote_file
|
||||
&& !storage_name.is_empty()
|
||||
&& !storage_key.is_empty()
|
||||
{
|
||||
let backend = crate::remote_storage::s3_tier::global_s3_tier_registry()
|
||||
.read()
|
||||
.unwrap()
|
||||
@@ -3659,7 +3666,7 @@ mod tests {
|
||||
dat_path = v.file_name(".dat");
|
||||
idx_path = v.file_name(".idx");
|
||||
assert!(Path::new(&dat_path).exists());
|
||||
v.destroy(false).unwrap();
|
||||
v.destroy(false, false).unwrap();
|
||||
}
|
||||
|
||||
assert!(!Path::new(&dat_path).exists());
|
||||
@@ -4424,7 +4431,7 @@ mod tests {
|
||||
assert!(std::path::Path::new(&idx_path).exists());
|
||||
|
||||
// Destroy the volume
|
||||
v.destroy(false).unwrap();
|
||||
v.destroy(false, false).unwrap();
|
||||
|
||||
// .dat and .idx should be gone
|
||||
assert!(
|
||||
@@ -4481,7 +4488,7 @@ mod tests {
|
||||
assert!(std::path::Path::new(&dat_path).exists());
|
||||
assert!(std::path::Path::new(&idx_path).exists());
|
||||
|
||||
v.destroy(false).unwrap();
|
||||
v.destroy(false, false).unwrap();
|
||||
|
||||
assert!(
|
||||
!std::path::Path::new(&dat_path).exists(),
|
||||
|
||||
@@ -74,25 +74,33 @@ func TestAssumeRoleWithWebIdentityValidation(t *testing.T) {
|
||||
assert.Equal(t, "MissingParameter", errResp.Error.Code)
|
||||
})
|
||||
|
||||
t.Run("missing_role_arn", func(t *testing.T) {
|
||||
t.Run("missing_role_arn_invalid_jwt_still_rejected", func(t *testing.T) {
|
||||
// Missing RoleArn is no longer a fast-fail at the HTTP layer:
|
||||
// claim-based policy mode (Phase 3b) advertises RoleArn as
|
||||
// optional so the STS service can derive the assumed-role ARN
|
||||
// from the configured policy claim. Validation now happens at
|
||||
// the STS layer once the JWT is parsed. With a bogus token the
|
||||
// JWT parse fails first, so the request is still rejected —
|
||||
// just with the JWT-parse error code instead of MissingParameter.
|
||||
resp, err := callSTSAPI(t, url.Values{
|
||||
"Action": {"AssumeRoleWithWebIdentity"},
|
||||
"WebIdentityToken": {"fake-jwt-token"},
|
||||
"RoleSessionName": {"test-session"},
|
||||
// RoleArn is missing
|
||||
// RoleArn omitted on purpose.
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
|
||||
"Should fail without RoleArn")
|
||||
"Should still fail when RoleArn is missing and the JWT is invalid")
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
var errResp STSErrorTestResponse
|
||||
err = xml.Unmarshal(body, &errResp)
|
||||
require.NoError(t, err, "Failed to parse error response: %s", string(body))
|
||||
assert.Equal(t, "MissingParameter", errResp.Error.Code)
|
||||
assert.NotEqual(t, "MissingParameter", errResp.Error.Code,
|
||||
"missing RoleArn alone must no longer surface as MissingParameter")
|
||||
})
|
||||
|
||||
t.Run("missing_role_session_name", func(t *testing.T) {
|
||||
|
||||
@@ -704,13 +704,27 @@ func uniqueName(prefix string) string {
|
||||
// --- Test setup helpers ---
|
||||
|
||||
func startMiniCluster(t *testing.T) (*TestCluster, error) {
|
||||
ports := testutil.MustAllocatePorts(t, 8)
|
||||
// Allocate two extra ports for admin HTTP + gRPC. Without explicit
|
||||
// values mini falls back to 23646/33646, which collide across the
|
||||
// sequential subtests in this package: each subtest spins up a fresh
|
||||
// mini in a goroutine, but the previous mini's admin goroutine is
|
||||
// still binding 23646 — so the next test's admin can never become
|
||||
// ready and mini.go fatals on its readiness check.
|
||||
ports := testutil.MustAllocatePorts(t, 10)
|
||||
masterPort, masterGrpcPort := ports[0], ports[1]
|
||||
volumePort, volumeGrpcPort := ports[2], ports[3]
|
||||
filerPort, filerGrpcPort := ports[4], ports[5]
|
||||
s3Port, s3GrpcPort := ports[6], ports[7]
|
||||
adminPort, adminGrpcPort := ports[8], ports[9]
|
||||
|
||||
testDir := t.TempDir()
|
||||
// Manually-managed temp dir (not t.TempDir()) so we control removal order:
|
||||
// the dir is removed inside Stop() AFTER the mini goroutine has fully
|
||||
// exited. Otherwise t.TempDir()'s RemoveAll cleanup races the admin
|
||||
// plugin worker, which keeps creating files under admin/plugin/job_types/
|
||||
// for ~1s after subtests finish, producing flaky "directory not empty"
|
||||
// failures (see seaweedfs CI run 25352039081).
|
||||
testDir, err := os.MkdirTemp("", "seaweed-policy-mini-")
|
||||
require.NoError(t, err)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
s3Endpoint := fmt.Sprintf("http://127.0.0.1:%d", s3Port)
|
||||
@@ -729,7 +743,7 @@ func startMiniCluster(t *testing.T) (*TestCluster, error) {
|
||||
|
||||
// Disable authentication for tests
|
||||
securityToml := filepath.Join(testDir, "security.toml")
|
||||
err := os.WriteFile(securityToml, []byte("# Empty security config\n"), 0644)
|
||||
err = os.WriteFile(securityToml, []byte("# Empty security config\n"), 0644)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Configure credential store for IAM tests.
|
||||
@@ -772,6 +786,8 @@ enabled = true
|
||||
"-filer.port.grpc=" + strconv.Itoa(filerGrpcPort),
|
||||
"-s3.port=" + strconv.Itoa(s3Port),
|
||||
"-s3.port.grpc=" + strconv.Itoa(s3GrpcPort),
|
||||
"-admin.port=" + strconv.Itoa(adminPort),
|
||||
"-admin.port.grpc=" + strconv.Itoa(adminGrpcPort),
|
||||
"-webdav.port=0",
|
||||
"-admin.ui=false",
|
||||
"-master.volumeSizeLimitMB=32",
|
||||
@@ -783,7 +799,12 @@ enabled = true
|
||||
for _, cmd := range command.Commands {
|
||||
if cmd.Name() == "mini" && cmd.Run != nil {
|
||||
cmd.Flag.Parse(os.Args[1:])
|
||||
// MiniClusterCtx makes runMini observe our cancel: master/
|
||||
// volume/filer get this as their shutdownCtx, and the clients
|
||||
// state (admin/s3/webdav/plugin worker) chains from it.
|
||||
command.MiniClusterCtx = ctx
|
||||
cmd.Run(cmd, cmd.Flag.Args())
|
||||
command.MiniClusterCtx = nil
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -792,6 +813,8 @@ enabled = true
|
||||
// Wait for S3
|
||||
if !testutil.WaitForService(cluster.s3Endpoint, 60*time.Second) {
|
||||
cancel()
|
||||
cluster.wg.Wait()
|
||||
os.RemoveAll(testDir)
|
||||
return nil, fmt.Errorf("timeout waiting for S3 at %s", cluster.s3Endpoint)
|
||||
}
|
||||
|
||||
@@ -799,6 +822,8 @@ enabled = true
|
||||
if os.Getenv("VOLUME_SERVER_IMPL") == "rust" {
|
||||
if err := cluster.startRustVolumeServer(t); err != nil {
|
||||
cancel()
|
||||
cluster.wg.Wait()
|
||||
os.RemoveAll(testDir)
|
||||
return nil, fmt.Errorf("failed to start Rust volume server: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -882,10 +907,25 @@ func (c *TestCluster) Stop() {
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
}
|
||||
if c.isRunning {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
// Wait for the mini goroutine to fully return before removing the data
|
||||
// dir. runMini observes MiniClusterCtx and returns once cancel fires; the
|
||||
// admin/s3/webdav/plugin-worker shutdown is gated by the same ctx via
|
||||
// resetMiniClients. The deadline is generous because admin shutdown can
|
||||
// take several seconds when graceful-stops are draining.
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
c.wg.Wait()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(15 * time.Second):
|
||||
fmt.Println("Warning: TestCluster.Stop timed out waiting for mini goroutine")
|
||||
}
|
||||
// Simplified stop
|
||||
|
||||
// Reset all mini flags so a subsequent in-process startMiniCluster sees
|
||||
// fresh state.
|
||||
for _, cmd := range command.Commands {
|
||||
if cmd.Name() == "mini" {
|
||||
cmd.Flag.VisitAll(func(f *flag.Flag) {
|
||||
@@ -894,6 +934,10 @@ func (c *TestCluster) Stop() {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if c.dataDir != "" {
|
||||
os.RemoveAll(c.dataDir)
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
RUN pip install --no-cache-dir \
|
||||
"deltalake==0.21.0" \
|
||||
"pyarrow==17.0.0" \
|
||||
"requests==2.32.3"
|
||||
|
||||
WORKDIR /app
|
||||
COPY delta_rs_writer.py /app/delta_rs_writer.py
|
||||
|
||||
ENTRYPOINT ["python3", "/app/delta_rs_writer.py"]
|
||||
@@ -0,0 +1,104 @@
|
||||
# Unity Catalog OSS integration tests
|
||||
|
||||
These tests run Unity Catalog OSS in Docker against an embedded SeaweedFS
|
||||
S3 endpoint. The `server.properties` mirrors the upstream playground at
|
||||
[`mds-in-a-box/unitycatalog-playground`](https://github.com/data-engineering-helpers/mds-in-a-box/tree/main/unitycatalog-playground).
|
||||
|
||||
| Test | Variant | Status |
|
||||
| --- | --- | --- |
|
||||
| `TestUnityCatalogDeltaIntegration` | static keys, `aws.masterRoleArn=` empty | passes; covers catalog/schema/EXTERNAL Delta CRUD against SeaweedFS-backed warehouse and asserts that UC's `/temporary-table-credentials` *cannot* vend usable creds with this configuration -- exactly the gap the playground reports. |
|
||||
| `TestUnityCatalogMasterRoleIntegration` | `aws.masterRoleArn=arn:aws:iam::000000000000:role/UnityCatalogVendedRole` | passes; proves SeaweedFS' STS endpoint accepts `sts:AssumeRole` for the role UC would use (Go SDK round-trip), and that UC starts and accepts CRUD when wired with the master-role config. UC's own StsClient still talks to real AWS regardless of `aws.endpoint` / `AWS_ENDPOINT_URL_STS` (UC bug, see below); that hop is logged via `t.Logf` rather than asserted. |
|
||||
| `TestUnityCatalogDeltaRsRoundTrip` | static keys + `delta-rs` Python client | passes; resolves table metadata through UC and writes/reads a real Delta table at the registered `storage_location` using `python:3.11-slim + deltalake` with the SeaweedFS test credentials. |
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker available locally (the tests call `docker run` / `docker build` directly).
|
||||
- A `weed` binary at the repo root (`weed/weed`) or on `$PATH`.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
go test -timeout 15m \
|
||||
-run 'TestUnityCatalog' \
|
||||
./test/s3tables/unity_catalog/...
|
||||
```
|
||||
|
||||
Pin a specific Unity Catalog image (defaults to
|
||||
`unitycatalog/unitycatalog:v0.4.0`):
|
||||
|
||||
```bash
|
||||
UC_IMAGE=unitycatalog/unitycatalog:main \
|
||||
go test -timeout 15m -run TestUnityCatalogDeltaIntegration \
|
||||
./test/s3tables/unity_catalog/...
|
||||
```
|
||||
|
||||
The tests self-skip when Docker is unavailable or no `weed` binary is on
|
||||
the path; running under `-short` also skips them.
|
||||
|
||||
## Why the static-key path can't vend usable creds
|
||||
|
||||
UC OSS' `AwsCredentialVendor.createPerBucketCredentialGenerator`:
|
||||
|
||||
```java
|
||||
if (config.getSessionToken() != null && !config.getSessionToken().isEmpty()) {
|
||||
return new AwsCredentialGenerator.StaticAwsCredentialGenerator(config);
|
||||
}
|
||||
return createStsCredentialGenerator(config);
|
||||
```
|
||||
|
||||
With `aws.masterRoleArn=` empty and `s3.sessionToken.0=` empty (this
|
||||
test's configuration), `/temporary-table-credentials` short-circuits with
|
||||
`"S3 bucket configuration not found."` before UC fires any STS call.
|
||||
Setting a stub `s3.sessionToken.0` switches UC to
|
||||
`StaticAwsCredentialGenerator` and the endpoint returns the static keys,
|
||||
but the response carries that stub session token -- SeaweedFS won't
|
||||
recognize it on the next S3 call, so the vended creds aren't usable for
|
||||
table I/O. Clients have to fall back to the static keys directly.
|
||||
|
||||
With `aws.masterRoleArn` set, UC's `AwsCredentialGenerator.StsAwsCredentialGenerator`
|
||||
builds the StsClient with only `.region(...)` and `.credentialsProvider(...)` --
|
||||
no `.endpointOverride()`. The SDK's generic env-var resolution doesn't kick in
|
||||
for that builder shape, so even with `AWS_ENDPOINT_URL_STS=...` (or the
|
||||
matching `aws.endpointUrlSts` Java property, or the catch-all
|
||||
`AWS_ENDPOINT_URL=...`) the StsClient still targets real AWS and gets back
|
||||
`InvalidClientTokenId`. Verified by pointing the env var at port 1: UC reports
|
||||
the same AWS-issued 403 that it reports against SeaweedFS, and a sniffer in
|
||||
front of SeaweedFS' STS port records zero traffic. SeaweedFS' STS handler
|
||||
itself works -- the Go SDK round-trip in `assumeRoleViaSeaweedFS` proves that
|
||||
against the same SeaweedFS instance.
|
||||
|
||||
UC's own AWS credential-vending tests don't catch this because they mock
|
||||
`StsClient` away entirely -- `BaseCRUDTestWithMockCredentials` injects a
|
||||
custom `stsClientBuilderSupplier` returning an `EchoAwsStsClient` that
|
||||
synthesizes credentials in-process, and `CloudCredentialVendorTest` uses
|
||||
`Mockito.mockStatic(StsClient.class)`. No test ever exercises the wire
|
||||
path between UC's Java SDK and a real STS endpoint, so the missing
|
||||
`endpointOverride` slipped through.
|
||||
|
||||
Fix is upstream in
|
||||
[unitycatalog/unitycatalog#1532](https://github.com/unitycatalog/unitycatalog/pull/1532),
|
||||
which adds an `aws.endpoint` property and applies it to both the StsClient
|
||||
and the S3Client builders. Until that lands, the master-role test logs
|
||||
the failure but does not assert it.
|
||||
|
||||
## What the tests actually validate today
|
||||
|
||||
- Unity Catalog accepts a SeaweedFS-backed `server.properties` and starts.
|
||||
- Catalog / schema / EXTERNAL Delta table CRUD all work against the
|
||||
SeaweedFS warehouse via the UC REST API.
|
||||
- SeaweedFS' STS endpoint correctly issues `sts:AssumeRole` credentials
|
||||
for the `UnityCatalogVendedRole` and those credentials are accepted on
|
||||
S3 round-trips (Go AWS SDK).
|
||||
- Delta-RS resolves a UC table's `storage_location` and can write/read Delta
|
||||
data through the SeaweedFS S3 endpoint with the test credentials.
|
||||
|
||||
## What is still pending
|
||||
|
||||
Nothing on the SeaweedFS side. The remaining gap (UC's StsClient ignoring
|
||||
endpoint config) needs a UC OSS patch upstream.
|
||||
|
||||
## MANAGED tables
|
||||
|
||||
Not exercised. UC OSS gates them behind `server.managed-table.enabled=true`
|
||||
and a two-step staging flow (`POST /staging-tables` then `POST /tables`);
|
||||
EXTERNAL Delta is the simpler path and what these tests cover.
|
||||
@@ -0,0 +1,184 @@
|
||||
package unity_catalog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ucClient struct {
|
||||
base string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func newUCClient(base string) *ucClient {
|
||||
return &ucClient{base: base + ucAPIBase, http: &http.Client{Timeout: 30 * time.Second}}
|
||||
}
|
||||
|
||||
type ucCreateCatalog struct {
|
||||
Name string `json:"name"`
|
||||
Comment string `json:"comment,omitempty"`
|
||||
StorageRoot string `json:"storage_root,omitempty"`
|
||||
}
|
||||
|
||||
type ucCatalogInfo struct {
|
||||
Name string `json:"name"`
|
||||
StorageRoot string `json:"storage_root"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
type ucCreateSchema struct {
|
||||
Name string `json:"name"`
|
||||
CatalogName string `json:"catalog_name"`
|
||||
}
|
||||
|
||||
type ucSchemaInfo struct {
|
||||
Name string `json:"name"`
|
||||
CatalogName string `json:"catalog_name"`
|
||||
FullName string `json:"full_name"`
|
||||
SchemaID string `json:"schema_id"`
|
||||
}
|
||||
|
||||
type ucColumn struct {
|
||||
Name string `json:"name"`
|
||||
TypeText string `json:"type_text"`
|
||||
TypeJSON string `json:"type_json,omitempty"`
|
||||
TypeName string `json:"type_name"`
|
||||
Position int `json:"position"`
|
||||
Nullable bool `json:"nullable"`
|
||||
}
|
||||
|
||||
type ucCreateTable struct {
|
||||
Name string `json:"name"`
|
||||
CatalogName string `json:"catalog_name"`
|
||||
SchemaName string `json:"schema_name"`
|
||||
TableType string `json:"table_type"`
|
||||
DataSourceFormat string `json:"data_source_format"`
|
||||
Columns []ucColumn `json:"columns"`
|
||||
StorageLocation string `json:"storage_location,omitempty"`
|
||||
}
|
||||
|
||||
type ucTableInfo struct {
|
||||
Name string `json:"name"`
|
||||
CatalogName string `json:"catalog_name"`
|
||||
SchemaName string `json:"schema_name"`
|
||||
TableType string `json:"table_type"`
|
||||
DataSourceFormat string `json:"data_source_format"`
|
||||
Columns []ucColumn `json:"columns"`
|
||||
StorageLocation string `json:"storage_location"`
|
||||
TableID string `json:"table_id"`
|
||||
}
|
||||
|
||||
type ucListTablesResp struct {
|
||||
Tables []ucTableInfo `json:"tables"`
|
||||
}
|
||||
|
||||
type ucAwsCreds struct {
|
||||
AccessKeyID string `json:"access_key_id"`
|
||||
SecretAccessKey string `json:"secret_access_key"`
|
||||
SessionToken string `json:"session_token"`
|
||||
}
|
||||
|
||||
type ucTempCreds struct {
|
||||
AwsTempCredentials *ucAwsCreds `json:"aws_temp_credentials"`
|
||||
ExpirationTime int64 `json:"expiration_time"`
|
||||
}
|
||||
|
||||
func (c *ucClient) createCatalog(ctx context.Context, in ucCreateCatalog) (*ucCatalogInfo, error) {
|
||||
var out ucCatalogInfo
|
||||
return &out, c.do(ctx, http.MethodPost, "/catalogs", in, &out)
|
||||
}
|
||||
|
||||
func (c *ucClient) deleteCatalog(ctx context.Context, name string) error {
|
||||
q := url.Values{"force": []string{"true"}}
|
||||
return c.do(ctx, http.MethodDelete, "/catalogs/"+url.PathEscape(name)+"?"+q.Encode(), nil, nil)
|
||||
}
|
||||
|
||||
func (c *ucClient) createSchema(ctx context.Context, in ucCreateSchema) (*ucSchemaInfo, error) {
|
||||
var out ucSchemaInfo
|
||||
return &out, c.do(ctx, http.MethodPost, "/schemas", in, &out)
|
||||
}
|
||||
|
||||
func (c *ucClient) deleteSchema(ctx context.Context, fullName string) error {
|
||||
q := url.Values{"force": []string{"true"}}
|
||||
return c.do(ctx, http.MethodDelete, "/schemas/"+url.PathEscape(fullName)+"?"+q.Encode(), nil, nil)
|
||||
}
|
||||
|
||||
func (c *ucClient) createTable(ctx context.Context, in ucCreateTable) (*ucTableInfo, error) {
|
||||
var out ucTableInfo
|
||||
return &out, c.do(ctx, http.MethodPost, "/tables", in, &out)
|
||||
}
|
||||
|
||||
func (c *ucClient) getTable(ctx context.Context, fullName string) (*ucTableInfo, error) {
|
||||
var out ucTableInfo
|
||||
return &out, c.do(ctx, http.MethodGet, "/tables/"+url.PathEscape(fullName), nil, &out)
|
||||
}
|
||||
|
||||
func (c *ucClient) listTables(ctx context.Context, catalog, schema string) ([]ucTableInfo, error) {
|
||||
var out ucListTablesResp
|
||||
q := url.Values{
|
||||
"catalog_name": []string{catalog},
|
||||
"schema_name": []string{schema},
|
||||
}
|
||||
path := "/tables?" + q.Encode()
|
||||
if err := c.do(ctx, http.MethodGet, path, nil, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out.Tables, nil
|
||||
}
|
||||
|
||||
func (c *ucClient) deleteTable(ctx context.Context, fullName string) error {
|
||||
return c.do(ctx, http.MethodDelete, "/tables/"+url.PathEscape(fullName), nil, nil)
|
||||
}
|
||||
|
||||
func (c *ucClient) generateTemporaryTableCredentials(ctx context.Context, tableID, op string) (*ucTempCreds, error) {
|
||||
body := map[string]string{"table_id": tableID, "operation": op}
|
||||
var out ucTempCreds
|
||||
return &out, c.do(ctx, http.MethodPost, "/temporary-table-credentials", body, &out)
|
||||
}
|
||||
|
||||
func (c *ucClient) do(ctx context.Context, method, path string, in any, out any) error {
|
||||
var body io.Reader
|
||||
if in != nil {
|
||||
buf, err := json.Marshal(in)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal %s %s: %w", method, path, err)
|
||||
}
|
||||
body = bytes.NewReader(buf)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.base+path, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if in != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// 10 MiB cap is well above any reasonable Unity Catalog response and
|
||||
// keeps a runaway server from OOMing the test runner.
|
||||
respBytes, err := io.ReadAll(io.LimitReader(resp.Body, 10*1024*1024))
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s %s: %w", method, path, err)
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("%s %s: status %d: %s", method, path, resp.StatusCode, strings.TrimSpace(string(respBytes)))
|
||||
}
|
||||
if out == nil || len(respBytes) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := json.Unmarshal(respBytes, out); err != nil {
|
||||
return fmt.Errorf("decode %s %s: %w (body=%s)", method, path, err, string(respBytes))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package unity_catalog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
)
|
||||
|
||||
// TestUnityCatalogDeltaRsRoundTrip writes and reads a real Delta table at
|
||||
// the registered storage_location using the delta-rs Python library inside
|
||||
// a Docker container. The script resolves table metadata from UC and uses the
|
||||
// test SeaweedFS credentials as delta-rs storage_options.
|
||||
func TestUnityCatalogDeltaRsRoundTrip(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in -short mode")
|
||||
}
|
||||
if !testutil.HasDocker() {
|
||||
t.Skip("docker not available")
|
||||
}
|
||||
|
||||
env := newTestEnv(t)
|
||||
defer env.cleanup(t)
|
||||
|
||||
t.Log(">>> starting SeaweedFS for delta-rs test...")
|
||||
env.startSeaweedFS(t, "")
|
||||
t.Log(">>> SeaweedFS ready")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
s3c := env.newHostS3Client(t, ctx)
|
||||
if _, err := s3c.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(ucWarehouse)}); err != nil {
|
||||
t.Fatalf("create warehouse bucket: %v", err)
|
||||
}
|
||||
|
||||
t.Log(">>> starting Unity Catalog server...")
|
||||
env.startUnityCatalog(t, ctx, ucServerOpts{})
|
||||
t.Log(">>> Unity Catalog ready")
|
||||
|
||||
uc := newUCClient(fmt.Sprintf("http://127.0.0.1:%d", env.ucHostPort))
|
||||
|
||||
suffix := time.Now().UnixNano()
|
||||
catalogName := fmt.Sprintf("seaweed_uc_delta_rs_%d", suffix)
|
||||
schemaName := fmt.Sprintf("ns_%d", suffix)
|
||||
tableName := fmt.Sprintf("delta_rs_%d", suffix)
|
||||
tableLocation := fmt.Sprintf("s3://%s/%s/%s/%s", ucWarehouse, ucWarehouseKey, schemaName, tableName)
|
||||
|
||||
defer func() {
|
||||
_ = uc.deleteTable(context.Background(), catalogName+"."+schemaName+"."+tableName)
|
||||
_ = uc.deleteSchema(context.Background(), catalogName+"."+schemaName)
|
||||
_ = uc.deleteCatalog(context.Background(), catalogName)
|
||||
}()
|
||||
|
||||
if _, err := uc.createCatalog(ctx, ucCreateCatalog{
|
||||
Name: catalogName,
|
||||
StorageRoot: fmt.Sprintf("s3://%s/%s", ucWarehouse, ucWarehouseKey),
|
||||
}); err != nil {
|
||||
t.Fatalf("create catalog: %v", err)
|
||||
}
|
||||
if _, err := uc.createSchema(ctx, ucCreateSchema{Name: schemaName, CatalogName: catalogName}); err != nil {
|
||||
t.Fatalf("create schema: %v", err)
|
||||
}
|
||||
created, err := uc.createTable(ctx, ucCreateTable{
|
||||
Name: tableName,
|
||||
CatalogName: catalogName,
|
||||
SchemaName: schemaName,
|
||||
TableType: "EXTERNAL",
|
||||
DataSourceFormat: "DELTA",
|
||||
Columns: []ucColumn{
|
||||
{Name: "id", TypeText: "long", TypeName: "LONG", TypeJSON: `{"name":"id","type":"long","nullable":true,"metadata":{}}`, Position: 0, Nullable: true},
|
||||
{Name: "value", TypeText: "string", TypeName: "STRING", TypeJSON: `{"name":"value","type":"string","nullable":true,"metadata":{}}`, Position: 1, Nullable: true},
|
||||
},
|
||||
StorageLocation: tableLocation,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create table: %v", err)
|
||||
}
|
||||
|
||||
testDir, err := filepath.Abs(".")
|
||||
if err != nil {
|
||||
t.Fatalf("abs: %v", err)
|
||||
}
|
||||
imageTag := fmt.Sprintf("seaweed-uc-delta-rs:%d", time.Now().UnixNano())
|
||||
|
||||
build := exec.CommandContext(ctx, "docker", "build", "-t", imageTag, "-f", "Dockerfile.delta-rs", ".")
|
||||
build.Dir = testDir
|
||||
if out, err := build.CombinedOutput(); err != nil {
|
||||
t.Fatalf("docker build delta-rs image: %v\n%s", err, out)
|
||||
}
|
||||
defer func() { _ = exec.Command("docker", "rmi", "-f", imageTag).Run() }()
|
||||
|
||||
ucURLForContainer := fmt.Sprintf("http://host.docker.internal:%d", env.ucHostPort)
|
||||
s3EndpointForContainer := fmt.Sprintf("http://host.docker.internal:%d", env.s3Port)
|
||||
|
||||
cmd := exec.CommandContext(ctx, "docker", "run", "--rm",
|
||||
"--add-host", "host.docker.internal:host-gateway",
|
||||
"-e", "UC_URL="+ucURLForContainer,
|
||||
"-e", "S3_ENDPOINT="+s3EndpointForContainer,
|
||||
"-e", "UC_CATALOG="+catalogName,
|
||||
"-e", "UC_SCHEMA="+schemaName,
|
||||
"-e", "UC_TABLE="+tableName,
|
||||
"-e", "UC_TABLE_ID="+created.TableID,
|
||||
"-e", "AWS_ACCESS_KEY_ID="+env.accessKey,
|
||||
"-e", "AWS_SECRET_ACCESS_KEY="+env.secretKey,
|
||||
imageTag,
|
||||
)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("delta-rs container failed: %v\noutput:\n%s", err, out)
|
||||
}
|
||||
got := string(out)
|
||||
if !strings.Contains(got, "DELTA_RS_OK rows=3") {
|
||||
t.Fatalf("expected DELTA_RS_OK rows=3 in output; got:\n%s", got)
|
||||
}
|
||||
t.Logf("delta-rs output: %s", strings.TrimSpace(got))
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Round-trip a Delta table through Unity Catalog using delta-rs.
|
||||
|
||||
Reads connection settings from environment variables:
|
||||
|
||||
UC_URL Unity Catalog REST base, e.g. http://host.docker.internal:8080
|
||||
S3_ENDPOINT SeaweedFS S3 endpoint reachable from the container
|
||||
UC_CATALOG Catalog name to operate against
|
||||
UC_SCHEMA Schema name
|
||||
UC_TABLE Table name
|
||||
UC_TABLE_ID Optional: pre-fetched table_id; falls back to GET /tables/{full_name}
|
||||
AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY
|
||||
Optional: direct S3 credentials. If omitted, the script
|
||||
asks UC for temporary table credentials.
|
||||
|
||||
Steps:
|
||||
|
||||
1. GET the table info from UC.
|
||||
2. Resolve S3 credentials from env or UC temporary-table-credentials.
|
||||
3. write_deltalake() a small pyarrow Table to storage_location.
|
||||
4. Read it back with DeltaTable() and assert row count.
|
||||
|
||||
Prints `DELTA_RS_OK rows=<n>` on success and exits 0; any failure exits 1.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import urllib.parse
|
||||
|
||||
import pyarrow as pa
|
||||
import requests
|
||||
from deltalake import DeltaTable, write_deltalake
|
||||
|
||||
|
||||
def must_env(name: str) -> str:
|
||||
value = os.environ.get(name)
|
||||
if not value:
|
||||
print(f"ERROR: required env var {name} is not set", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
return value
|
||||
|
||||
|
||||
def main() -> int:
|
||||
uc_url = must_env("UC_URL").rstrip("/")
|
||||
s3_endpoint = must_env("S3_ENDPOINT")
|
||||
catalog = must_env("UC_CATALOG")
|
||||
schema = must_env("UC_SCHEMA")
|
||||
table = must_env("UC_TABLE")
|
||||
table_id = os.environ.get("UC_TABLE_ID", "").strip()
|
||||
|
||||
full_name = f"{catalog}.{schema}.{table}"
|
||||
api = f"{uc_url}/api/2.1/unity-catalog"
|
||||
|
||||
encoded_full_name = urllib.parse.quote(full_name, safe="")
|
||||
r = requests.get(f"{api}/tables/{encoded_full_name}", timeout=10)
|
||||
r.raise_for_status()
|
||||
info = r.json()
|
||||
if not table_id:
|
||||
table_id = info.get("table_id") or ""
|
||||
storage_location = info.get("storage_location") or ""
|
||||
|
||||
if not table_id:
|
||||
print("ERROR: table_id is empty in UC response", file=sys.stderr)
|
||||
return 1
|
||||
if not storage_location:
|
||||
print("ERROR: storage_location is empty in UC response", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
access_key = os.environ.get("AWS_ACCESS_KEY_ID", "").strip()
|
||||
secret_key = os.environ.get("AWS_SECRET_ACCESS_KEY", "").strip()
|
||||
session_token = os.environ.get("AWS_SESSION_TOKEN", "").strip()
|
||||
if bool(access_key) != bool(secret_key):
|
||||
print(
|
||||
"ERROR: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must be set together",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
if not access_key:
|
||||
creds_resp = requests.post(
|
||||
f"{api}/temporary-table-credentials",
|
||||
json={"table_id": table_id, "operation": "READ_WRITE"},
|
||||
timeout=15,
|
||||
)
|
||||
creds_resp.raise_for_status()
|
||||
creds = creds_resp.json().get("aws_temp_credentials") or {}
|
||||
access_key = creds.get("access_key_id") or ""
|
||||
secret_key = creds.get("secret_access_key") or ""
|
||||
session_token = creds.get("session_token") or ""
|
||||
if not access_key or not secret_key:
|
||||
print(
|
||||
"ERROR: missing aws_temp_credentials; "
|
||||
f"response status {creds_resp.status_code}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
storage_options = {
|
||||
"AWS_ACCESS_KEY_ID": access_key,
|
||||
"AWS_SECRET_ACCESS_KEY": secret_key,
|
||||
"AWS_REGION": "us-east-1",
|
||||
"AWS_ENDPOINT_URL": s3_endpoint,
|
||||
"AWS_ALLOW_HTTP": "true",
|
||||
# delta-rs requires this for non-S3 backends that lack atomic rename.
|
||||
"AWS_S3_ALLOW_UNSAFE_RENAME": "true",
|
||||
}
|
||||
if session_token:
|
||||
storage_options["AWS_SESSION_TOKEN"] = session_token
|
||||
|
||||
arrow_table = pa.table(
|
||||
{
|
||||
"id": pa.array([1, 2, 3], type=pa.int64()),
|
||||
"value": pa.array(["alpha", "beta", "gamma"], type=pa.string()),
|
||||
}
|
||||
)
|
||||
|
||||
write_deltalake(
|
||||
storage_location,
|
||||
arrow_table,
|
||||
storage_options=storage_options,
|
||||
mode="overwrite",
|
||||
)
|
||||
|
||||
dt = DeltaTable(storage_location, storage_options=storage_options)
|
||||
read_back = dt.to_pyarrow_table()
|
||||
rows = read_back.num_rows
|
||||
print(f"DELTA_RS_OK rows={rows} version={dt.version()}")
|
||||
return 0 if rows == arrow_table.num_rows else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
exit_code = main()
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
# deltalake/pyarrow can abort during native teardown after a successful
|
||||
# round-trip in the short-lived test container. Preserve main's result.
|
||||
os._exit(exit_code)
|
||||
@@ -0,0 +1,201 @@
|
||||
package unity_catalog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"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/aws-sdk-go-v2/service/sts"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
)
|
||||
|
||||
// TestUnityCatalogMasterRoleIntegration covers the master-role configuration
|
||||
// the upstream playground notes as not-yet-working
|
||||
// (https://github.com/data-engineering-helpers/mds-in-a-box/blob/main/unitycatalog-playground/etc/conf/server.properties#L45).
|
||||
//
|
||||
// It verifies two things end-to-end:
|
||||
//
|
||||
// 1. SeaweedFS' STS endpoint accepts sts:AssumeRole for the
|
||||
// UnityCatalogVendedRole, returning real STS-vended credentials. This
|
||||
// mirrors what the lakekeeper / polaris tests already exercise via the Go
|
||||
// AWS SDK and is the SeaweedFS-side prerequisite for UC's master-role
|
||||
// flow.
|
||||
//
|
||||
// 2. Unity Catalog OSS starts and accepts catalog/schema/EXTERNAL Delta
|
||||
// table CRUD when configured with `aws.masterRoleArn` set to that role
|
||||
// and AWS_ENDPOINT_URL_STS pointed at SeaweedFS.
|
||||
//
|
||||
// What it does NOT verify is the third hop -- UC's Java StsClient
|
||||
// reaching SeaweedFS' STS handler. UC's
|
||||
// AwsCredentialGenerator.StsAwsCredentialGenerator builds the StsClient
|
||||
// without an endpointOverride and doesn't propagate aws.endpoint to it, so
|
||||
// the SDK's generic AWS_ENDPOINT_URL_STS resolution doesn't kick in and the
|
||||
// request always targets real AWS, returning InvalidClientTokenId. Verified
|
||||
// by pointing AWS_ENDPOINT_URL_STS at port 1: same 403 either way, and a
|
||||
// sniffer in front of SeaweedFS records zero traffic. UC's own tests mock
|
||||
// StsClient out (BaseCRUDTestWithMockCredentials' EchoAwsStsClient,
|
||||
// Mockito.mockStatic in CloudCredentialVendorTest), so this never showed
|
||||
// up upstream. Fix is in unitycatalog/unitycatalog#1532; that bit is
|
||||
// logged via t.Logf and not asserted.
|
||||
func TestUnityCatalogMasterRoleIntegration(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in -short mode")
|
||||
}
|
||||
if !testutil.HasDocker() {
|
||||
t.Skip("docker not available")
|
||||
}
|
||||
|
||||
env := newTestEnv(t)
|
||||
defer env.cleanup(t)
|
||||
|
||||
t.Log(">>> starting SeaweedFS with STS-enabled IAM config...")
|
||||
env.startSeaweedFS(t, stsEnabledIAMConfig(env.accessKey, env.secretKey))
|
||||
t.Log(">>> SeaweedFS ready")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
s3c := env.newHostS3Client(t, ctx)
|
||||
if _, err := s3c.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(ucWarehouse)}); err != nil {
|
||||
t.Fatalf("create warehouse bucket: %v", err)
|
||||
}
|
||||
|
||||
// Slice 1: prove SeaweedFS STS works for the role UC would use.
|
||||
t.Run("SeaweedFsAssumesUnityCatalogVendedRole", func(t *testing.T) {
|
||||
stsEndpoint := fmt.Sprintf("http://127.0.0.1:%d", env.s3Port)
|
||||
creds, err := assumeRoleViaSeaweedFS(ctx, stsEndpoint, env.accessKey, env.secretKey, ucVendedRoleArn)
|
||||
if err != nil {
|
||||
t.Fatalf("AssumeRole on SeaweedFS STS: %v", err)
|
||||
}
|
||||
if creds.SessionToken == "" {
|
||||
t.Fatalf("expected non-empty session_token from STS, got %+v", creds)
|
||||
}
|
||||
if creds.AccessKeyID == env.accessKey {
|
||||
t.Fatalf("STS returned the static admin access key; AssumeRole did not vend a new one")
|
||||
}
|
||||
|
||||
// Confirm the vended creds actually work for an S3 round-trip.
|
||||
s3v := env.newHostS3ClientWithCreds(t, ctx, creds.AccessKeyID, creds.SecretAccessKey, creds.SessionToken)
|
||||
probeKey := "ns-probe/master-role-probe.txt"
|
||||
if _, err := s3v.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(ucWarehouse),
|
||||
Key: aws.String(probeKey),
|
||||
Body: nil,
|
||||
}); err != nil {
|
||||
t.Fatalf("PutObject with sts-vended creds: %v", err)
|
||||
}
|
||||
_, _ = s3v.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(ucWarehouse),
|
||||
Key: aws.String(probeKey),
|
||||
})
|
||||
})
|
||||
|
||||
// Slice 2: UC starts with master-role config and CRUD works.
|
||||
stsEndpoint := fmt.Sprintf("http://host.docker.internal:%d", env.s3Port)
|
||||
t.Log(">>> starting Unity Catalog server (master role)...")
|
||||
env.startUnityCatalog(t, ctx, ucServerOpts{
|
||||
MasterRoleArn: ucVendedRoleArn,
|
||||
ExtraEnv: map[string]string{
|
||||
"AWS_ENDPOINT_URL": stsEndpoint,
|
||||
"AWS_ENDPOINT_URL_STS": stsEndpoint,
|
||||
"AWS_ACCESS_KEY_ID": env.accessKey,
|
||||
"AWS_SECRET_ACCESS_KEY": env.secretKey,
|
||||
"AWS_REGION": "us-east-1",
|
||||
},
|
||||
})
|
||||
t.Log(">>> Unity Catalog ready")
|
||||
|
||||
uc := newUCClient(fmt.Sprintf("http://127.0.0.1:%d", env.ucHostPort))
|
||||
suffix := time.Now().UnixNano()
|
||||
catalogName := fmt.Sprintf("seaweed_uc_role_%d", suffix)
|
||||
schemaName := fmt.Sprintf("ns_%d", suffix)
|
||||
tableName := fmt.Sprintf("events_%d", suffix)
|
||||
tableLocation := fmt.Sprintf("s3://%s/%s/%s/%s", ucWarehouse, ucWarehouseKey, schemaName, tableName)
|
||||
|
||||
defer func() {
|
||||
_ = uc.deleteTable(context.Background(), catalogName+"."+schemaName+"."+tableName)
|
||||
_ = uc.deleteSchema(context.Background(), catalogName+"."+schemaName)
|
||||
_ = uc.deleteCatalog(context.Background(), catalogName)
|
||||
}()
|
||||
|
||||
t.Run("UnityCatalogAcceptsMasterRoleConfig", func(t *testing.T) {
|
||||
if _, err := uc.createCatalog(ctx, ucCreateCatalog{
|
||||
Name: catalogName,
|
||||
StorageRoot: fmt.Sprintf("s3://%s/%s", ucWarehouse, ucWarehouseKey),
|
||||
}); err != nil {
|
||||
t.Fatalf("create catalog: %v", err)
|
||||
}
|
||||
if _, err := uc.createSchema(ctx, ucCreateSchema{Name: schemaName, CatalogName: catalogName}); err != nil {
|
||||
t.Fatalf("create schema: %v", err)
|
||||
}
|
||||
created, err := uc.createTable(ctx, ucCreateTable{
|
||||
Name: tableName,
|
||||
CatalogName: catalogName,
|
||||
SchemaName: schemaName,
|
||||
TableType: "EXTERNAL",
|
||||
DataSourceFormat: "DELTA",
|
||||
Columns: []ucColumn{
|
||||
{Name: "id", TypeText: "long", TypeName: "LONG", TypeJSON: `{"name":"id","type":"long","nullable":true,"metadata":{}}`, Position: 0, Nullable: true},
|
||||
},
|
||||
StorageLocation: tableLocation,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create external delta table: %v", err)
|
||||
}
|
||||
if created.TableID == "" {
|
||||
t.Fatalf("expected table_id in CreateTable response, got %+v", created)
|
||||
}
|
||||
|
||||
// The actual UC -> SeaweedFS STS handoff is the still-unsolved slice.
|
||||
// Log what happens, but don't fail the test on it: SeaweedFS' STS is
|
||||
// known-good (slice 1 above), and UC's CRUD is known-good (this slice).
|
||||
_, ucCredErr := uc.generateTemporaryTableCredentials(ctx, created.TableID, "READ_WRITE")
|
||||
if ucCredErr != nil {
|
||||
t.Logf("UC StsClient still hits real AWS (UC bug, fix in unitycatalog/unitycatalog#1532): %v", ucCredErr)
|
||||
} else {
|
||||
t.Logf("UC StsClient honors endpoint override; unitycatalog/unitycatalog#1532 (or equivalent) is in this image.")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// assumeRoleViaSeaweedFS calls sts:AssumeRole against SeaweedFS' STS endpoint
|
||||
// using the Go AWS SDK, mirroring how lakekeeper/polaris tests prove
|
||||
// SeaweedFS' STS path works.
|
||||
func assumeRoleViaSeaweedFS(ctx context.Context, endpoint, accessKey, secretKey, roleArn string) (aws.Credentials, error) {
|
||||
cfg, err := config.LoadDefaultConfig(ctx,
|
||||
config.WithRegion("us-east-1"),
|
||||
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")),
|
||||
)
|
||||
if err != nil {
|
||||
return aws.Credentials{}, fmt.Errorf("load aws config: %w", err)
|
||||
}
|
||||
|
||||
// Override the STS endpoint via service-specific BaseEndpoint instead of
|
||||
// the deprecated EndpointResolverWithOptions wired through the global
|
||||
// config. This is the supported path in aws-sdk-go-v2 since v1.21.
|
||||
client := sts.NewFromConfig(cfg, func(o *sts.Options) {
|
||||
o.BaseEndpoint = aws.String(endpoint)
|
||||
})
|
||||
resp, err := client.AssumeRole(ctx, &sts.AssumeRoleInput{
|
||||
RoleArn: aws.String(roleArn),
|
||||
RoleSessionName: aws.String("uc-master-role-test"),
|
||||
})
|
||||
if err != nil {
|
||||
return aws.Credentials{}, err
|
||||
}
|
||||
if resp.Credentials == nil {
|
||||
return aws.Credentials{}, fmt.Errorf("AssumeRole returned no credentials")
|
||||
}
|
||||
return aws.Credentials{
|
||||
AccessKeyID: aws.ToString(resp.Credentials.AccessKeyId),
|
||||
SecretAccessKey: aws.ToString(resp.Credentials.SecretAccessKey),
|
||||
SessionToken: aws.ToString(resp.Credentials.SessionToken),
|
||||
Source: "seaweedfs-sts",
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
package unity_catalog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"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/seaweedfs/seaweedfs/test/testutil"
|
||||
)
|
||||
|
||||
const (
|
||||
ucImageDefault = "unitycatalog/unitycatalog:v0.4.0"
|
||||
ucContainerCfg = "/home/unitycatalog/etc/conf/server.properties"
|
||||
ucStartupGrace = 90 * time.Second
|
||||
ucAPIBase = "/api/2.1/unity-catalog"
|
||||
ucWarehouse = "lakehouse"
|
||||
ucWarehouseKey = "warehouse"
|
||||
|
||||
// Role used by the master-role STS-vended variant of the test. The trust
|
||||
// policy is wide open so any caller can assume it; in production UC
|
||||
// would set this ARN as `aws.masterRoleArn`.
|
||||
ucVendedRoleArn = "arn:aws:iam::000000000000:role/UnityCatalogVendedRole"
|
||||
ucVendedRoleName = "UnityCatalogVendedRole"
|
||||
)
|
||||
|
||||
type testEnv struct {
|
||||
seaweedDir string
|
||||
weedBinary string
|
||||
dataDir string
|
||||
bindIP string
|
||||
s3Port int
|
||||
s3GrpcPort int
|
||||
masterPort int
|
||||
masterGrpcPort int
|
||||
filerPort int
|
||||
filerGrpcPort int
|
||||
volumePort int
|
||||
volumeGrpcPort int
|
||||
weedProcess *exec.Cmd
|
||||
weedCancel context.CancelFunc
|
||||
|
||||
accessKey string
|
||||
secretKey string
|
||||
|
||||
ucImage string
|
||||
ucContainerID string
|
||||
ucHostPort int
|
||||
}
|
||||
|
||||
// ucServerOpts customizes the Unity Catalog server.properties and runtime
|
||||
// environment. Defaults match the upstream playground (static keys, no master
|
||||
// role).
|
||||
type ucServerOpts struct {
|
||||
// MasterRoleArn populates aws.masterRoleArn. Empty means UC falls back to
|
||||
// static aws.accessKey / aws.secretKey for storage operations.
|
||||
MasterRoleArn string
|
||||
// ExtraEnv adds environment variables to the UC container, useful for
|
||||
// AWS_ENDPOINT_URL_STS-style overrides.
|
||||
ExtraEnv map[string]string
|
||||
}
|
||||
|
||||
func newTestEnv(t *testing.T) *testEnv {
|
||||
t.Helper()
|
||||
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("getwd: %v", err)
|
||||
}
|
||||
seaweedDir := wd
|
||||
for i := 0; i < 8; i++ {
|
||||
if _, err := os.Stat(filepath.Join(seaweedDir, "go.mod")); err == nil {
|
||||
break
|
||||
}
|
||||
seaweedDir = filepath.Dir(seaweedDir)
|
||||
}
|
||||
|
||||
weedBinary := filepath.Join(seaweedDir, "weed", "weed")
|
||||
if _, err := os.Stat(weedBinary); err != nil {
|
||||
weedBinary = "weed"
|
||||
if _, err := exec.LookPath(weedBinary); err != nil {
|
||||
t.Skip("weed binary not found, skipping integration test")
|
||||
}
|
||||
}
|
||||
|
||||
dataDir, err := os.MkdirTemp("", "seaweed-uc-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("mkdtemp: %v", err)
|
||||
}
|
||||
|
||||
bindIP := testutil.FindBindIP()
|
||||
ports := testutil.MustAllocatePorts(t, 9)
|
||||
masterPort, masterGrpcPort := ports[0], ports[1]
|
||||
volumePort, volumeGrpcPort := ports[2], ports[3]
|
||||
filerPort, filerGrpcPort := ports[4], ports[5]
|
||||
s3Port, s3GrpcPort := ports[6], ports[7]
|
||||
ucHostPort := ports[8]
|
||||
|
||||
image := os.Getenv("UC_IMAGE")
|
||||
if image == "" {
|
||||
image = ucImageDefault
|
||||
}
|
||||
|
||||
return &testEnv{
|
||||
seaweedDir: seaweedDir,
|
||||
weedBinary: weedBinary,
|
||||
dataDir: dataDir,
|
||||
bindIP: bindIP,
|
||||
s3Port: s3Port,
|
||||
s3GrpcPort: s3GrpcPort,
|
||||
masterPort: masterPort,
|
||||
masterGrpcPort: masterGrpcPort,
|
||||
filerPort: filerPort,
|
||||
filerGrpcPort: filerGrpcPort,
|
||||
volumePort: volumePort,
|
||||
volumeGrpcPort: volumeGrpcPort,
|
||||
accessKey: "admin",
|
||||
secretKey: "admin",
|
||||
ucImage: image,
|
||||
ucHostPort: ucHostPort,
|
||||
}
|
||||
}
|
||||
|
||||
// startSeaweedFS starts a `weed mini` instance. If iamJSON is empty, a minimal
|
||||
// admin-only IAM config is used. When iamJSON is non-empty, it is passed to
|
||||
// both -s3.config and -s3.iam.config so the STS handler is enabled (mirroring
|
||||
// the lakekeeper test).
|
||||
func (env *testEnv) startSeaweedFS(t *testing.T, iamJSON string) {
|
||||
t.Helper()
|
||||
|
||||
enableSTS := iamJSON != ""
|
||||
if iamJSON == "" {
|
||||
iamJSON = fmt.Sprintf(`{
|
||||
"identities": [
|
||||
{
|
||||
"name": "admin",
|
||||
"credentials": [{"accessKey": %q, "secretKey": %q}],
|
||||
"actions": ["Admin", "Read", "List", "Tagging", "Write"]
|
||||
}
|
||||
]
|
||||
}`, env.accessKey, env.secretKey)
|
||||
}
|
||||
|
||||
iamConfigPath := filepath.Join(env.dataDir, "iam.json")
|
||||
if err := os.WriteFile(iamConfigPath, []byte(iamJSON), 0644); err != nil {
|
||||
t.Fatalf("write iam config: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
env.weedCancel = cancel
|
||||
|
||||
weedArgs := []string{"-v", "4", "mini",
|
||||
"-master.port", fmt.Sprintf("%d", env.masterPort),
|
||||
"-master.port.grpc", fmt.Sprintf("%d", env.masterGrpcPort),
|
||||
"-volume.port", fmt.Sprintf("%d", env.volumePort),
|
||||
"-volume.port.grpc", fmt.Sprintf("%d", env.volumeGrpcPort),
|
||||
"-filer.port", fmt.Sprintf("%d", env.filerPort),
|
||||
"-filer.port.grpc", fmt.Sprintf("%d", env.filerGrpcPort),
|
||||
"-s3.port", fmt.Sprintf("%d", env.s3Port),
|
||||
"-s3.port.grpc", fmt.Sprintf("%d", env.s3GrpcPort),
|
||||
"-s3.config", iamConfigPath,
|
||||
"-ip", env.bindIP,
|
||||
"-ip.bind", "0.0.0.0",
|
||||
"-dir", env.dataDir,
|
||||
}
|
||||
if enableSTS {
|
||||
weedArgs = append(weedArgs, "-s3.iam.config", iamConfigPath, "-s3.iam.readOnly=false")
|
||||
}
|
||||
|
||||
cmd := exec.CommandContext(ctx, env.weedBinary, weedArgs...)
|
||||
cmd.Dir = env.dataDir
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("start weed mini: %v", err)
|
||||
}
|
||||
env.weedProcess = cmd
|
||||
|
||||
if !testutil.WaitForService(fmt.Sprintf("http://127.0.0.1:%d/status", env.s3Port), testutil.SeaweedMiniStartupTimeout) {
|
||||
t.Fatalf("S3 API at 127.0.0.1:%d did not become ready", env.s3Port)
|
||||
}
|
||||
}
|
||||
|
||||
// startUnityCatalog launches the Unity Catalog OSS server in Docker against
|
||||
// the running SeaweedFS instance. It mirrors the upstream playground's
|
||||
// server.properties layout and bind-mounts only that single file (matching
|
||||
// docker-compose.yaml from the playground).
|
||||
func (env *testEnv) startUnityCatalog(t *testing.T, ctx context.Context, opts ucServerOpts) {
|
||||
t.Helper()
|
||||
|
||||
s3EndpointForContainer := fmt.Sprintf("http://host.docker.internal:%d", env.s3Port)
|
||||
|
||||
props := strings.Join([]string{
|
||||
"server.env=test",
|
||||
"server.authorization=disable",
|
||||
"server.cookie-timeout=PT1H",
|
||||
"server.managed-table.enabled=false",
|
||||
fmt.Sprintf("aws.masterRoleArn=%s", opts.MasterRoleArn),
|
||||
fmt.Sprintf("aws.accessKey=%s", env.accessKey),
|
||||
fmt.Sprintf("aws.secretKey=%s", env.secretKey),
|
||||
"aws.region=us-east-1",
|
||||
fmt.Sprintf("aws.endpoint=%s", s3EndpointForContainer),
|
||||
// UC keys perBucketS3Configs by NormalizedURL.from(bucketPath) and
|
||||
// looks up using the storageBase, which is "s3://<bucket>" (scheme +
|
||||
// authority only). The playground's "s3://lakehouse/warehouse" never
|
||||
// matches because of that asymmetry; the bucket-only form works.
|
||||
fmt.Sprintf("s3.bucketPath.0=s3://%s", ucWarehouse),
|
||||
"s3.region.0=us-east-1",
|
||||
fmt.Sprintf("s3.awsRoleArn.0=%s", opts.MasterRoleArn),
|
||||
fmt.Sprintf("s3.accessKey.0=%s", env.accessKey),
|
||||
fmt.Sprintf("s3.secretKey.0=%s", env.secretKey),
|
||||
fmt.Sprintf("s3.endpoint.0=%s", s3EndpointForContainer),
|
||||
"",
|
||||
}, "\n")
|
||||
|
||||
confDir := filepath.Join(env.dataDir, "uc-conf")
|
||||
if err := os.MkdirAll(confDir, 0755); err != nil {
|
||||
t.Fatalf("mkdir uc-conf: %v", err)
|
||||
}
|
||||
propsPath := filepath.Join(confDir, "server.properties")
|
||||
if err := os.WriteFile(propsPath, []byte(props), 0644); err != nil {
|
||||
t.Fatalf("write server.properties: %v", err)
|
||||
}
|
||||
|
||||
containerName := fmt.Sprintf("seaweed-unity-catalog-%d", time.Now().UnixNano())
|
||||
|
||||
args := []string{
|
||||
"run", "-d", "--rm",
|
||||
"--name", containerName,
|
||||
"--add-host", "host.docker.internal:host-gateway",
|
||||
"-p", fmt.Sprintf("%d:8080", env.ucHostPort),
|
||||
"-v", fmt.Sprintf("%s:%s:ro", propsPath, ucContainerCfg),
|
||||
"-e", "JAVA_OPTS=-Xmx1g",
|
||||
}
|
||||
for k, v := range opts.ExtraEnv {
|
||||
args = append(args, "-e", fmt.Sprintf("%s=%s", k, v))
|
||||
}
|
||||
args = append(args, env.ucImage)
|
||||
|
||||
out, err := exec.CommandContext(ctx, "docker", args...).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("docker run unity-catalog: %v\n%s", err, out)
|
||||
}
|
||||
// docker run -d prefixes pull progress / warnings before the final container
|
||||
// ID line when the image isn't cached locally. Trim to the last whitespace-
|
||||
// separated token so the ID survives a fresh CI runner.
|
||||
fields := strings.Fields(string(out))
|
||||
if len(fields) == 0 {
|
||||
t.Fatalf("docker run produced no output; combined: %q", string(out))
|
||||
}
|
||||
env.ucContainerID = fields[len(fields)-1]
|
||||
t.Logf("unity-catalog container id: %s", env.ucContainerID)
|
||||
|
||||
probe := fmt.Sprintf("http://127.0.0.1:%d%s/catalogs", env.ucHostPort, ucAPIBase)
|
||||
deadline := time.Now().Add(ucStartupGrace)
|
||||
var lastErr error
|
||||
for time.Now().Before(deadline) {
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, probe, nil)
|
||||
resp, err := (&http.Client{Timeout: 3 * time.Second}).Do(req)
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
return
|
||||
}
|
||||
lastErr = fmt.Errorf("status %d", resp.StatusCode)
|
||||
} else {
|
||||
lastErr = err
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("ctx done while waiting for unity catalog: %v", ctx.Err())
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
logs, _ := exec.Command("docker", "logs", "--tail", "200", env.ucContainerID).CombinedOutput()
|
||||
t.Fatalf("unity catalog did not become ready: %v\nrecent logs:\n%s", lastErr, logs)
|
||||
}
|
||||
|
||||
func (env *testEnv) cleanup(t *testing.T) {
|
||||
if env.ucContainerID != "" {
|
||||
if logs, err := exec.Command("docker", "logs", "--tail", "200", env.ucContainerID).CombinedOutput(); err == nil {
|
||||
t.Logf("unity-catalog tail logs:\n%s", logs)
|
||||
}
|
||||
_ = exec.Command("docker", "rm", "-f", env.ucContainerID).Run()
|
||||
}
|
||||
if env.weedCancel != nil {
|
||||
env.weedCancel()
|
||||
}
|
||||
if env.weedProcess != nil {
|
||||
_ = env.weedProcess.Wait()
|
||||
}
|
||||
if env.dataDir != "" {
|
||||
_ = os.RemoveAll(env.dataDir)
|
||||
}
|
||||
}
|
||||
|
||||
// -- S3 client helpers ---------------------------------------------------------
|
||||
|
||||
func (env *testEnv) newHostS3Client(t *testing.T, ctx context.Context) *s3.Client {
|
||||
t.Helper()
|
||||
return env.newHostS3ClientWithCreds(t, ctx, env.accessKey, env.secretKey, "")
|
||||
}
|
||||
|
||||
func (env *testEnv) newHostS3ClientWithCreds(t *testing.T, ctx context.Context, ak, sk, token string) *s3.Client {
|
||||
t.Helper()
|
||||
endpoint := fmt.Sprintf("http://127.0.0.1:%d", env.s3Port)
|
||||
cfg, err := config.LoadDefaultConfig(ctx,
|
||||
config.WithRegion("us-east-1"),
|
||||
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(ak, sk, token)),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("load aws config: %v", err)
|
||||
}
|
||||
return s3.NewFromConfig(cfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(endpoint)
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
}
|
||||
|
||||
// stsEnabledIAMConfig returns an iam.json that defines an admin user, the
|
||||
// UnityCatalogVendedRole role with a permissive trust policy, and a FullAccess
|
||||
// policy attached to it. This is the SeaweedFS-side counterpart of the
|
||||
// `aws.masterRoleArn` configuration on the Unity Catalog server.
|
||||
func stsEnabledIAMConfig(accessKey, secretKey string) string {
|
||||
return fmt.Sprintf(`{
|
||||
"identities": [
|
||||
{
|
||||
"name": "admin",
|
||||
"credentials": [{"accessKey": %q, "secretKey": %q}],
|
||||
"actions": ["Admin", "Read", "List", "Tagging", "Write"]
|
||||
}
|
||||
],
|
||||
"sts": {
|
||||
"tokenDuration": "12h",
|
||||
"maxSessionLength": "24h",
|
||||
"issuer": "seaweedfs-sts",
|
||||
"signingKey": "dGVzdC1zaWduaW5nLWtleS1mb3Itc3RzLWludGVncmF0aW9uLXRlc3Rz"
|
||||
},
|
||||
"roles": [
|
||||
{
|
||||
"roleName": %q,
|
||||
"roleArn": %q,
|
||||
"trustPolicy": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "sts:AssumeRole"
|
||||
}
|
||||
]
|
||||
},
|
||||
"attachedPolicies": ["FullAccess"]
|
||||
}
|
||||
],
|
||||
"policies": [
|
||||
{
|
||||
"name": "FullAccess",
|
||||
"document": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{"Effect": "Allow", "Action": "*", "Resource": "*"}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}`, accessKey, secretKey, ucVendedRoleName, ucVendedRoleArn)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
// Package unity_catalog provides integration tests that run Unity Catalog
|
||||
// OSS in Docker against a SeaweedFS S3 backend. The base test mirrors the
|
||||
// configuration used by the upstream UC playground at
|
||||
// https://github.com/data-engineering-helpers/mds-in-a-box/tree/main/unitycatalog-playground:
|
||||
// static aws.accessKey/aws.secretKey, no master role, EXTERNAL Delta tables.
|
||||
package unity_catalog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
)
|
||||
|
||||
// TestUnityCatalogDeltaIntegration brings up SeaweedFS, runs Unity Catalog OSS
|
||||
// in Docker against it, and exercises catalog/schema/table CRUD plus
|
||||
// temporary-table-credentials and storage I/O via vended credentials. The UC
|
||||
// server is configured with static keys (aws.masterRoleArn empty), matching
|
||||
// the playground's working configuration when targeting SeaweedFS.
|
||||
func TestUnityCatalogDeltaIntegration(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in -short mode")
|
||||
}
|
||||
if !testutil.HasDocker() {
|
||||
t.Skip("docker not available")
|
||||
}
|
||||
|
||||
env := newTestEnv(t)
|
||||
defer env.cleanup(t)
|
||||
|
||||
t.Log(">>> starting SeaweedFS for Unity Catalog test...")
|
||||
env.startSeaweedFS(t, "")
|
||||
t.Log(">>> SeaweedFS ready")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
s3c := env.newHostS3Client(t, ctx)
|
||||
if _, err := s3c.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(ucWarehouse)}); err != nil {
|
||||
t.Fatalf("create warehouse bucket: %v", err)
|
||||
}
|
||||
|
||||
t.Log(">>> starting Unity Catalog server (static keys)...")
|
||||
env.startUnityCatalog(t, ctx, ucServerOpts{})
|
||||
t.Log(">>> Unity Catalog ready")
|
||||
|
||||
uc := newUCClient(fmt.Sprintf("http://127.0.0.1:%d", env.ucHostPort))
|
||||
|
||||
suffix := time.Now().UnixNano()
|
||||
catalogName := fmt.Sprintf("seaweed_uc_%d", suffix)
|
||||
schemaName := fmt.Sprintf("ns_%d", suffix)
|
||||
tableName := fmt.Sprintf("events_%d", suffix)
|
||||
tableLocation := fmt.Sprintf("s3://%s/%s/%s/%s", ucWarehouse, ucWarehouseKey, schemaName, tableName)
|
||||
|
||||
defer func() {
|
||||
_ = uc.deleteTable(context.Background(), catalogName+"."+schemaName+"."+tableName)
|
||||
_ = uc.deleteSchema(context.Background(), catalogName+"."+schemaName)
|
||||
_ = uc.deleteCatalog(context.Background(), catalogName)
|
||||
}()
|
||||
|
||||
t.Run("CreateCatalog", func(t *testing.T) {
|
||||
got, err := uc.createCatalog(ctx, ucCreateCatalog{
|
||||
Name: catalogName,
|
||||
Comment: "seaweedfs integration test",
|
||||
StorageRoot: fmt.Sprintf("s3://%s/%s", ucWarehouse, ucWarehouseKey),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create catalog: %v", err)
|
||||
}
|
||||
if got.Name != catalogName {
|
||||
t.Fatalf("catalog name = %q, want %q", got.Name, catalogName)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("CreateSchema", func(t *testing.T) {
|
||||
got, err := uc.createSchema(ctx, ucCreateSchema{
|
||||
Name: schemaName,
|
||||
CatalogName: catalogName,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create schema: %v", err)
|
||||
}
|
||||
if got.Name != schemaName || got.CatalogName != catalogName {
|
||||
t.Fatalf("schema = %+v, want name=%q catalog=%q", got, schemaName, catalogName)
|
||||
}
|
||||
})
|
||||
|
||||
var createdTable ucTableInfo
|
||||
t.Run("CreateExternalDeltaTable", func(t *testing.T) {
|
||||
columns := []ucColumn{
|
||||
{Name: "id", TypeText: "long", TypeName: "LONG", TypeJSON: `{"name":"id","type":"long","nullable":true,"metadata":{}}`, Position: 0, Nullable: true},
|
||||
{Name: "value", TypeText: "string", TypeName: "STRING", TypeJSON: `{"name":"value","type":"string","nullable":true,"metadata":{}}`, Position: 1, Nullable: true},
|
||||
}
|
||||
got, err := uc.createTable(ctx, ucCreateTable{
|
||||
Name: tableName,
|
||||
CatalogName: catalogName,
|
||||
SchemaName: schemaName,
|
||||
TableType: "EXTERNAL",
|
||||
DataSourceFormat: "DELTA",
|
||||
Columns: columns,
|
||||
StorageLocation: tableLocation,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create table: %v", err)
|
||||
}
|
||||
if got.TableType != "EXTERNAL" || got.DataSourceFormat != "DELTA" {
|
||||
t.Fatalf("table types = %s/%s, want EXTERNAL/DELTA", got.TableType, got.DataSourceFormat)
|
||||
}
|
||||
if got.StorageLocation == "" {
|
||||
t.Fatalf("table storage_location is empty in response: %+v", got)
|
||||
}
|
||||
createdTable = *got
|
||||
})
|
||||
|
||||
t.Run("GetTable", func(t *testing.T) {
|
||||
full := catalogName + "." + schemaName + "." + tableName
|
||||
got, err := uc.getTable(ctx, full)
|
||||
if err != nil {
|
||||
t.Fatalf("get table: %v", err)
|
||||
}
|
||||
if got.Name != tableName {
|
||||
t.Fatalf("get table name = %q, want %q", got.Name, tableName)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ListTables", func(t *testing.T) {
|
||||
tables, err := uc.listTables(ctx, catalogName, schemaName)
|
||||
if err != nil {
|
||||
t.Fatalf("list tables: %v", err)
|
||||
}
|
||||
found := false
|
||||
for _, tbl := range tables {
|
||||
if tbl.Name == tableName {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("created table %q not found in list", tableName)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("TemporaryTableCredentialsRejected", func(t *testing.T) {
|
||||
// With aws.masterRoleArn empty AND no s3.sessionToken.0 set, UC OSS
|
||||
// always tries to AssumeRole via its internal StsClient (see
|
||||
// AwsCredentialVendor.createPerBucketCredentialGenerator). Against a
|
||||
// non-AWS endpoint, that call doesn't reach a real STS, so UC returns
|
||||
// "S3 bucket configuration not found." or an STS-side error. This is
|
||||
// the gap users hit at <https://github.com/data-engineering-helpers/mds-in-a-box/blob/main/unitycatalog-playground/etc/conf/server.properties#L45>:
|
||||
// "with simple S3 access and secret keys, Unity Catalog does not seem
|
||||
// to work."
|
||||
//
|
||||
// The assertion is therefore inverted: we expect a non-nil error from
|
||||
// /temporary-table-credentials with this configuration. A future
|
||||
// variant can pin s3.sessionToken.0 (UC's StaticAwsCredentialGenerator
|
||||
// path) once SeaweedFS' SigV4 path tolerates the vended session token.
|
||||
if createdTable.TableID == "" {
|
||||
t.Fatalf("created table has empty table_id; cannot request temporary credentials")
|
||||
}
|
||||
_, err := uc.generateTemporaryTableCredentials(ctx, createdTable.TableID, "READ_WRITE")
|
||||
if err == nil {
|
||||
t.Fatalf("expected /temporary-table-credentials to fail with the static-key playground configuration; it succeeded unexpectedly")
|
||||
}
|
||||
t.Logf("expected failure (UC static-key path requires AWS STS): %v", err)
|
||||
})
|
||||
|
||||
t.Run("DeleteTableSchemaCatalog", func(t *testing.T) {
|
||||
if err := uc.deleteTable(ctx, catalogName+"."+schemaName+"."+tableName); err != nil {
|
||||
t.Fatalf("delete table: %v", err)
|
||||
}
|
||||
if err := uc.deleteSchema(ctx, catalogName+"."+schemaName); err != nil {
|
||||
t.Fatalf("delete schema: %v", err)
|
||||
}
|
||||
if err := uc.deleteCatalog(ctx, catalogName); err != nil {
|
||||
t.Fatalf("delete catalog: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -123,6 +123,7 @@ func (ms *MaintenanceScanner) getVolumeHealthMetrics() ([]*types.VolumeHealthMet
|
||||
DeletedBytes: volInfo.DeletedByteCount,
|
||||
LastModified: time.Unix(int64(volInfo.ModifiedAtSecond), 0),
|
||||
IsReadOnly: volInfo.ReadOnly,
|
||||
HasRemoteCopy: volInfo.RemoteStorageName != "",
|
||||
IsECVolume: false, // Will be determined from volume structure
|
||||
ReplicaCount: 1, // Will be counted
|
||||
ExpectedReplicas: int(volInfo.ReplicaPlacement),
|
||||
|
||||
@@ -758,7 +758,7 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
}
|
||||
|
||||
function updateURL(replace) {
|
||||
var url = buildPluginURL(state.activeTopTab, state.activeSubTab, state.selectedJobType);
|
||||
var url = basePath(buildPluginURL(state.activeTopTab, state.activeSubTab, state.selectedJobType));
|
||||
if (replace) {
|
||||
history.replaceState({ pluginTopTab: state.activeTopTab, pluginSubTab: state.activeSubTab, pluginJob: state.selectedJobType }, '', url);
|
||||
} else {
|
||||
|
||||
@@ -104,7 +104,7 @@ func Plugin(page string, initialJob string, lane string) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</p></div><div class=\"btn-group\"><button type=\"button\" class=\"btn btn-outline-secondary\" id=\"plugin-refresh-all-btn\"><i class=\"fas fa-sync-alt me-1\"></i>Refresh</button></div></div></div></div><div class=\"row mb-3\"><div class=\"col-12\"><ul class=\"nav nav-tabs\" id=\"plugin-top-tabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-top-tab=\"overview\"><i class=\"fas fa-chart-line me-1\"></i>Overview</button></li></ul></div></div><div class=\"row mb-3 d-none\" id=\"plugin-subtab-row\"><div class=\"col-12\"><ul class=\"nav nav-pills gap-2\" id=\"plugin-subtabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-subtab=\"configuration\"><i class=\"fas fa-sliders-h me-1\"></i>Configuration</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"detection\"><i class=\"fas fa-search me-1\"></i>Job Detection</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"queue\"><i class=\"fas fa-list me-1\"></i>Job Queue</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"execution\"><i class=\"fas fa-tasks me-1\"></i>Job Execution</button></li></ul></div></div><div class=\"plugin-section plugin-section-overview\"><div class=\"row mb-4\"><div class=\"col-md-3 mb-3\"><div class=\"card border-info h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Workers</div><h4 class=\"mb-0\" id=\"plugin-status-workers\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-warning h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Active Jobs</div><h4 class=\"mb-0\" id=\"plugin-status-active-jobs\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-success h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Activities (recent)</div><h4 class=\"mb-0\" id=\"plugin-status-activities\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-secondary h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Next Run</div><h4 class=\"mb-0 plugin-scheduler-next-run\">-</h4><div class=\"text-muted small plugin-scheduler-next-run-meta\"></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"fas fa-chart-bar me-2\"></i>Per Job Type Summary</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Active Jobs</th><th>Recent Activities</th></tr></thead> <tbody id=\"plugin-jobtype-summary-body\"><tr><td colspan=\"3\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"fas fa-clock me-2\"></i>Scheduler State</h5><small class=\"text-muted\">Sequential scheduler with per-job runtime limits</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Enabled</th><th>Detector</th><th>In Flight</th><th>Max Runtime</th><th>Exec Global</th><th>Exec/Worker</th><th>Executor Workers</th><th>Effective Exec</th><th>Last Run</th></tr></thead> <tbody id=\"plugin-scheduler-table-body\"><tr><td colspan=\"10\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"fas fa-users me-2\"></i>Workers</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Worker</th><th>Address</th><th>Capabilities</th><th>Load</th></tr></thead> <tbody id=\"plugin-workers-table-body\"><tr><td colspan=\"4\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-configuration\"><div class=\"row mb-4\"><div class=\"col-lg-8 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"fas fa-sliders-h me-2\"></i>Job Type Configuration</h5><small class=\"text-muted\" id=\"plugin-config-updated-at\">Not loaded</small></div><div class=\"card-body\"><div class=Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</p></div><div class=\"btn-group\"><button type=\"button\" class=\"btn btn-outline-secondary\" id=\"plugin-refresh-all-btn\"><i class=\"fas fa-sync-alt me-1\"></i>Refresh</button></div></div></div></div><div class=\"row mb-3\"><div class=\"col-12\"><ul class=\"nav nav-tabs\" id=\"plugin-top-tabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-top-tab=\"overview\"><i class=\"fas fa-chart-line me-1\"></i>Overview</button></li></ul></div></div><div class=\"row mb-3 d-none\" id=\"plugin-subtab-row\"><div class=\"col-12\"><ul class=\"nav nav-pills gap-2\" id=\"plugin-subtabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-subtab=\"configuration\"><i class=\"fas fa-sliders-h me-1\"></i>Configuration</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"detection\"><i class=\"fas fa-search me-1\"></i>Job Detection</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"queue\"><i class=\"fas fa-list me-1\"></i>Job Queue</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"execution\"><i class=\"fas fa-tasks me-1\"></i>Job Execution</button></li></ul></div></div><div class=\"plugin-section plugin-section-overview\"><div class=\"row mb-4\"><div class=\"col-md-3 mb-3\"><div class=\"card border-info h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Workers</div><h4 class=\"mb-0\" id=\"plugin-status-workers\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-warning h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Active Jobs</div><h4 class=\"mb-0\" id=\"plugin-status-active-jobs\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-success h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Activities (recent)</div><h4 class=\"mb-0\" id=\"plugin-status-activities\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-secondary h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Next Run</div><h4 class=\"mb-0 plugin-scheduler-next-run\">-</h4><div class=\"text-muted small plugin-scheduler-next-run-meta\"></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"fas fa-chart-bar me-2\"></i>Per Job Type Summary</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Active Jobs</th><th>Recent Activities</th></tr></thead> <tbody id=\"plugin-jobtype-summary-body\"><tr><td colspan=\"3\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"fas fa-clock me-2\"></i>Scheduler State</h5><small class=\"text-muted\">Sequential scheduler with per-job runtime limits</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Enabled</th><th>Detector</th><th>In Flight</th><th>Max Runtime</th><th>Exec Global</th><th>Exec/Worker</th><th>Executor Workers</th><th>Effective Exec</th><th>Last Run</th></tr></thead> <tbody id=\"plugin-scheduler-table-body\"><tr><td colspan=\"10\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"fas fa-users me-2\"></i>Workers</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Worker</th><th>Address</th><th>Capabilities</th><th>Load</th></tr></thead> <tbody id=\"plugin-workers-table-body\"><tr><td colspan=\"4\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-configuration\"><div class=\"row mb-4\"><div class=\"col-lg-8 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"fas fa-sliders-h me-2\"></i>Job Type Configuration</h5><small class=\"text-muted\" id=\"plugin-config-updated-at\">Not loaded</small></div><div class=\"card-body\"><div class=Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ func backupFromLocation(volumeServer pb.ServerAddress, grpcDialOption grpc.DialO
|
||||
|
||||
// If local volume is larger than remote, recreate it
|
||||
if datSize > stats.TailOffset {
|
||||
if err := v.Destroy(false); err != nil {
|
||||
if err := v.Destroy(false, false); err != nil {
|
||||
v.Close()
|
||||
return fmt.Errorf("destroying volume: %w", err), false
|
||||
}
|
||||
|
||||
+29
-5
@@ -1253,7 +1253,15 @@ func startMiniAdminWithWorker(allServicesReady chan struct{}) {
|
||||
// Wait for admin server's HTTP port to be ready before launching worker
|
||||
adminAddr := fmt.Sprintf("http://%s:%d", bindIp, *miniAdminOptions.port)
|
||||
glog.V(1).Infof("Waiting for admin server to be ready at %s...", adminAddr)
|
||||
if err := waitForAdminServerReady(adminAddr); err != nil {
|
||||
if err := waitForAdminServerReady(ctx, adminAddr); err != nil {
|
||||
// If the parent context was cancelled (e.g. a previous in-process
|
||||
// mini run is being torn down), bail out gracefully instead of
|
||||
// fataling — the test harness uses `cmd.Run` directly so a Fatalf
|
||||
// would terminate the entire test binary.
|
||||
if ctx.Err() != nil {
|
||||
glog.Warningf("Admin server readiness wait aborted: %v", err)
|
||||
return
|
||||
}
|
||||
glog.Fatalf("Admin server readiness check failed: %v", err)
|
||||
}
|
||||
|
||||
@@ -1272,16 +1280,28 @@ func startMiniAdminWithWorker(allServicesReady chan struct{}) {
|
||||
waitForWorkerReady(workerGrpcAddr)
|
||||
}
|
||||
|
||||
// waitForAdminServerReady pings the admin server HTTP endpoint to check if it's ready
|
||||
func waitForAdminServerReady(adminAddr string) error {
|
||||
// waitForAdminServerReady pings the admin server HTTP endpoint to check if it's ready.
|
||||
// Returns ctx.Err() (typically context.Canceled) if the parent context is
|
||||
// cancelled mid-poll so a torn-down mini doesn't keep spinning for the full
|
||||
// timeout — relevant when tests embed mini in-process and reuse the same
|
||||
// goroutine pool across subtests.
|
||||
func waitForAdminServerReady(ctx context.Context, adminAddr string) error {
|
||||
healthAddr := getHealthCheckAddr(fmt.Sprintf("%s/health", adminAddr))
|
||||
maxAttempts := 60 // 60 * 500ms = 30 seconds max wait
|
||||
// 240 * 500ms = 120 seconds max wait. The previous 30-second ceiling was
|
||||
// too tight on busy CI runners where master + filer + volume + admin all
|
||||
// initialise on a shared worker — the S3 Policy Shell Integration Tests
|
||||
// flaked regularly even though the admin server still came up within a
|
||||
// minute or two. Two minutes leaves headroom without being absurd locally.
|
||||
maxAttempts := 240
|
||||
attempt := 0
|
||||
client := &http.Client{
|
||||
Timeout: 1 * time.Second,
|
||||
}
|
||||
|
||||
for attempt < maxAttempts {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := client.Get(healthAddr)
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
@@ -1289,7 +1309,11 @@ func waitForAdminServerReady(adminAddr string) error {
|
||||
return nil
|
||||
}
|
||||
attempt++
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("admin server did not become ready at %s after %d attempts", adminAddr, maxAttempts)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetProviderByIssuerAndAccount(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewMemoryOIDCProviderStore()
|
||||
|
||||
// Two providers for the same issuer, scoped to different accounts.
|
||||
must := func(rec *OIDCProviderRecord) {
|
||||
if err := store.StoreProvider(ctx, "", rec); err != nil {
|
||||
t.Fatalf("store: %v", err)
|
||||
}
|
||||
}
|
||||
must(&OIDCProviderRecord{
|
||||
AccountID: "111",
|
||||
ARN: "arn:aws:iam::111:oidc-provider/idp.example",
|
||||
URL: "https://idp.example",
|
||||
ClientIDs: []string{"a"},
|
||||
})
|
||||
must(&OIDCProviderRecord{
|
||||
AccountID: "222",
|
||||
ARN: "arn:aws:iam::222:oidc-provider/idp.example",
|
||||
URL: "https://idp.example",
|
||||
ClientIDs: []string{"b"},
|
||||
})
|
||||
|
||||
t.Run("matching account returns scoped record", func(t *testing.T) {
|
||||
rec, err := store.GetProviderByIssuerAndAccount(ctx, "", "https://idp.example", "111")
|
||||
if err != nil {
|
||||
t.Fatalf("err: %v", err)
|
||||
}
|
||||
if rec.AccountID != "111" {
|
||||
t.Fatalf("unexpected record: %+v", rec)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unknown account is rejected", func(t *testing.T) {
|
||||
if _, err := store.GetProviderByIssuerAndAccount(ctx, "", "https://idp.example", "999"); err == nil {
|
||||
t.Fatal("expected error for cross-account use")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("global provider satisfies any account", func(t *testing.T) {
|
||||
must(&OIDCProviderRecord{
|
||||
AccountID: "",
|
||||
ARN: "arn:aws:iam:::oidc-provider/global.example",
|
||||
URL: "https://global.example",
|
||||
ClientIDs: []string{"x"},
|
||||
})
|
||||
rec, err := store.GetProviderByIssuerAndAccount(ctx, "", "https://global.example", "anything")
|
||||
if err != nil {
|
||||
t.Fatalf("err: %v", err)
|
||||
}
|
||||
if rec.AccountID != "" {
|
||||
t.Fatalf("expected global record, got AccountID=%q", rec.AccountID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty caller account accepts any record", func(t *testing.T) {
|
||||
rec, err := store.GetProviderByIssuerAndAccount(ctx, "", "https://idp.example", "")
|
||||
if err != nil {
|
||||
t.Fatalf("err: %v", err)
|
||||
}
|
||||
if rec == nil {
|
||||
t.Fatal("expected a record")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -4,11 +4,15 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/oidc"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/providers"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
@@ -23,14 +27,333 @@ const maxPoliciesForEvaluation = 1024
|
||||
|
||||
// IAMManager orchestrates all IAM components
|
||||
type IAMManager struct {
|
||||
stsService *sts.STSService
|
||||
policyEngine *policy.PolicyEngine
|
||||
roleStore RoleStore
|
||||
userStore UserStore
|
||||
filerAddressProvider func() string // Function to get current filer address
|
||||
initialized bool
|
||||
runtimePolicyMu sync.Mutex
|
||||
runtimePolicyNames map[string]struct{}
|
||||
stsService *sts.STSService
|
||||
policyEngine *policy.PolicyEngine
|
||||
roleStore RoleStore
|
||||
userStore UserStore
|
||||
oidcProviderStore OIDCProviderStore
|
||||
oidcAuditSink OIDCProviderAuditSink
|
||||
revocationStore SessionRevocationStore
|
||||
filerAddressProvider func() string // Function to get current filer address
|
||||
initialized bool
|
||||
runtimePolicyMu sync.Mutex
|
||||
runtimePolicyNames map[string]struct{}
|
||||
}
|
||||
|
||||
// SetOIDCProviderAuditSink configures the lifecycle event sink. When nil
|
||||
// (default), GlogAuditSink is used so events still surface in logs.
|
||||
func (m *IAMManager) SetOIDCProviderAuditSink(sink OIDCProviderAuditSink) {
|
||||
m.oidcAuditSink = sink
|
||||
}
|
||||
|
||||
// emitOIDCAudit logs a lifecycle event. Errors are swallowed: an audit
|
||||
// failure must never block an IAM mutation that has already succeeded.
|
||||
func (m *IAMManager) emitOIDCAudit(ctx context.Context, eventType OIDCProviderAuditEventType, arn, url string, detail map[string]string) {
|
||||
sink := m.oidcAuditSink
|
||||
if sink == nil {
|
||||
sink = GlogAuditSink{}
|
||||
}
|
||||
event := &OIDCProviderAuditEvent{
|
||||
Type: eventType,
|
||||
ARN: arn,
|
||||
URL: url,
|
||||
Detail: detail,
|
||||
OccurredAt: time.Now().UTC(),
|
||||
}
|
||||
if err := sink.Emit(ctx, event); err != nil {
|
||||
glog.Warningf("OIDC audit emit %s for %s: %v", eventType, arn, err)
|
||||
}
|
||||
}
|
||||
|
||||
// SetSessionRevocationStore configures the per-session revocation list. When
|
||||
// nil, RevokeSession returns an error and IsSessionRevoked is a no-op (every
|
||||
// session is considered live until natural expiry). Operators who want
|
||||
// revocation must wire a store explicitly.
|
||||
func (m *IAMManager) SetSessionRevocationStore(store SessionRevocationStore) {
|
||||
m.revocationStore = store
|
||||
}
|
||||
|
||||
// RevokeSession marks a session as revoked using its JTI (which equals the
|
||||
// session ID for STS-issued tokens).
|
||||
func (m *IAMManager) RevokeSession(ctx context.Context, jti string, expiresAt time.Time, reason string) error {
|
||||
if m.revocationStore == nil {
|
||||
return fmt.Errorf("session revocation store not configured")
|
||||
}
|
||||
if jti == "" {
|
||||
return fmt.Errorf("jti cannot be empty")
|
||||
}
|
||||
return m.revocationStore.Revoke(ctx, m.getFilerAddress(), &RevocationEntry{
|
||||
JTI: jti,
|
||||
ExpiresAt: expiresAt,
|
||||
Reason: reason,
|
||||
})
|
||||
}
|
||||
|
||||
// IsSessionRevoked returns true if the given JTI has been revoked. Returns
|
||||
// false (with nil error) when no revocation store is configured.
|
||||
func (m *IAMManager) IsSessionRevoked(ctx context.Context, jti string) (bool, error) {
|
||||
if m.revocationStore == nil || jti == "" {
|
||||
return false, nil
|
||||
}
|
||||
return m.revocationStore.IsRevoked(ctx, m.getFilerAddress(), jti)
|
||||
}
|
||||
|
||||
// PurgeRevokedSessions removes revocation entries whose underlying session
|
||||
// has already expired. Safe to call on a cron schedule.
|
||||
func (m *IAMManager) PurgeRevokedSessions(ctx context.Context) (int, error) {
|
||||
if m.revocationStore == nil {
|
||||
return 0, nil
|
||||
}
|
||||
return m.revocationStore.Purge(ctx, m.getFilerAddress(), time.Now().UTC())
|
||||
}
|
||||
|
||||
// SetOIDCProviderStore configures the IAM-managed OIDC provider store. When
|
||||
// nil, OIDC provider IAM actions return ServiceNotReady. The store is the
|
||||
// source of truth for AssumeRoleWithWebIdentity provider resolution once
|
||||
// Phase 2b lands; in Phase 2a it is read-only and populated from static
|
||||
// configuration at boot.
|
||||
func (m *IAMManager) SetOIDCProviderStore(store OIDCProviderStore) {
|
||||
m.oidcProviderStore = store
|
||||
}
|
||||
|
||||
// GetOIDCProviderStore returns the configured store (may be nil).
|
||||
func (m *IAMManager) GetOIDCProviderStore() OIDCProviderStore {
|
||||
return m.oidcProviderStore
|
||||
}
|
||||
|
||||
// GetOIDCProvider returns the record for the given ARN, or an error if the
|
||||
// store is not configured or the record is missing.
|
||||
func (m *IAMManager) GetOIDCProvider(ctx context.Context, arn string) (*OIDCProviderRecord, error) {
|
||||
if m.oidcProviderStore == nil {
|
||||
return nil, fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
return m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
}
|
||||
|
||||
// ListOIDCProviders enumerates all configured OIDC providers.
|
||||
func (m *IAMManager) ListOIDCProviders(ctx context.Context) ([]*OIDCProviderRecord, error) {
|
||||
if m.oidcProviderStore == nil {
|
||||
return nil, fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
return m.oidcProviderStore.ListProviders(ctx, m.getFilerAddress())
|
||||
}
|
||||
|
||||
// CreateOIDCProvider persists a new IAM-managed OIDC provider record. Refuses
|
||||
// to overwrite an existing record so callers see EntityAlreadyExists semantics.
|
||||
func (m *IAMManager) CreateOIDCProvider(ctx context.Context, rec *OIDCProviderRecord) error {
|
||||
if m.oidcProviderStore == nil {
|
||||
return fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
if rec == nil {
|
||||
return fmt.Errorf("record cannot be nil")
|
||||
}
|
||||
if err := validateOIDCProviderRecord(rec); err != nil {
|
||||
return err
|
||||
}
|
||||
existing, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), rec.ARN)
|
||||
if err == nil && existing != nil {
|
||||
return fmt.Errorf("%w: %s", ErrOIDCProviderAlreadyExists, rec.ARN)
|
||||
}
|
||||
if err != nil && !errors.Is(err, ErrOIDCProviderNotFound) {
|
||||
return fmt.Errorf("lookup existing OIDC provider %q: %w", rec.ARN, err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
rec.CreatedAt = now
|
||||
rec.UpdatedAt = now
|
||||
if err := m.oidcProviderStore.StoreProvider(ctx, m.getFilerAddress(), rec); err != nil {
|
||||
return err
|
||||
}
|
||||
m.refreshOIDCProvidersBestEffort(ctx, "CreateOIDCProvider", rec.ARN)
|
||||
m.emitOIDCAudit(ctx, OIDCAuditEventCreated, rec.ARN, rec.URL, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteOIDCProvider removes the IAM-managed record. Idempotent.
|
||||
func (m *IAMManager) DeleteOIDCProvider(ctx context.Context, arn string) error {
|
||||
if m.oidcProviderStore == nil {
|
||||
return fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
if err := m.oidcProviderStore.DeleteProvider(ctx, m.getFilerAddress(), arn); err != nil {
|
||||
return err
|
||||
}
|
||||
m.refreshOIDCProvidersBestEffort(ctx, "DeleteOIDCProvider", arn)
|
||||
m.emitOIDCAudit(ctx, OIDCAuditEventDeleted, arn, "", nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddClientIDToOIDCProvider appends `clientID` to the provider's allowed
|
||||
// audience list. Adding an existing client ID is a no-op (AWS-compat).
|
||||
func (m *IAMManager) AddClientIDToOIDCProvider(ctx context.Context, arn, clientID string) error {
|
||||
if m.oidcProviderStore == nil {
|
||||
return fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
if clientID == "" {
|
||||
return fmt.Errorf("ClientID cannot be empty")
|
||||
}
|
||||
rec, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, existing := range rec.ClientIDs {
|
||||
if existing == clientID {
|
||||
return nil // idempotent
|
||||
}
|
||||
}
|
||||
if len(rec.ClientIDs) >= 100 {
|
||||
return fmt.Errorf("ClientIDList must contain at most 100 entries")
|
||||
}
|
||||
rec.ClientIDs = append(rec.ClientIDs, clientID)
|
||||
rec.UpdatedAt = time.Now().UTC()
|
||||
if err := m.oidcProviderStore.StoreProvider(ctx, m.getFilerAddress(), rec); err != nil {
|
||||
return err
|
||||
}
|
||||
m.refreshOIDCProvidersBestEffort(ctx, "AddClientIDToOIDCProvider", arn)
|
||||
m.emitOIDCAudit(ctx, OIDCAuditEventClientIDAdded, rec.ARN, rec.URL, map[string]string{"clientId": clientID})
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveClientIDFromOIDCProvider drops `clientID` from the allowed audience
|
||||
// list. Removing a missing client ID is a no-op.
|
||||
func (m *IAMManager) RemoveClientIDFromOIDCProvider(ctx context.Context, arn, clientID string) error {
|
||||
if m.oidcProviderStore == nil {
|
||||
return fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
rec, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pruned := make([]string, 0, len(rec.ClientIDs))
|
||||
for _, existing := range rec.ClientIDs {
|
||||
if existing != clientID {
|
||||
pruned = append(pruned, existing)
|
||||
}
|
||||
}
|
||||
if len(pruned) == len(rec.ClientIDs) {
|
||||
return nil // not present; no-op
|
||||
}
|
||||
rec.ClientIDs = pruned
|
||||
rec.UpdatedAt = time.Now().UTC()
|
||||
if err := m.oidcProviderStore.StoreProvider(ctx, m.getFilerAddress(), rec); err != nil {
|
||||
return err
|
||||
}
|
||||
m.refreshOIDCProvidersBestEffort(ctx, "RemoveClientIDFromOIDCProvider", arn)
|
||||
m.emitOIDCAudit(ctx, OIDCAuditEventClientIDRemoved, rec.ARN, rec.URL, map[string]string{"clientId": clientID})
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateOIDCProviderThumbprints replaces the entire thumbprint list. AWS
|
||||
// constrains the list to 1..5 entries when non-empty; we mirror that bound.
|
||||
func (m *IAMManager) UpdateOIDCProviderThumbprints(ctx context.Context, arn string, thumbprints []string) error {
|
||||
if m.oidcProviderStore == nil {
|
||||
return fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
if len(thumbprints) > 5 {
|
||||
return fmt.Errorf("ThumbprintList must contain at most 5 entries, got %d", len(thumbprints))
|
||||
}
|
||||
for _, tp := range thumbprints {
|
||||
if !isValidSHA1Thumbprint(tp) {
|
||||
return fmt.Errorf("invalid thumbprint %q: must be 40-character SHA-1 hex", tp)
|
||||
}
|
||||
}
|
||||
rec, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rec.Thumbprints = append([]string(nil), thumbprints...)
|
||||
rec.UpdatedAt = time.Now().UTC()
|
||||
if err := m.oidcProviderStore.StoreProvider(ctx, m.getFilerAddress(), rec); err != nil {
|
||||
return err
|
||||
}
|
||||
m.refreshOIDCProvidersBestEffort(ctx, "UpdateOIDCProviderThumbprints", arn)
|
||||
m.emitOIDCAudit(ctx, OIDCAuditEventThumbprintsSet, rec.ARN, rec.URL, map[string]string{"count": fmt.Sprintf("%d", len(thumbprints))})
|
||||
return nil
|
||||
}
|
||||
|
||||
// TagOIDCProvider merges the supplied tags into the provider's tag set.
|
||||
func (m *IAMManager) TagOIDCProvider(ctx context.Context, arn string, tags map[string]string) error {
|
||||
if m.oidcProviderStore == nil {
|
||||
return fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
rec, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rec.Tags == nil {
|
||||
rec.Tags = make(map[string]string, len(tags))
|
||||
}
|
||||
for k, v := range tags {
|
||||
rec.Tags[k] = v
|
||||
}
|
||||
rec.UpdatedAt = time.Now().UTC()
|
||||
if err := m.oidcProviderStore.StoreProvider(ctx, m.getFilerAddress(), rec); err != nil {
|
||||
return err
|
||||
}
|
||||
m.emitOIDCAudit(ctx, OIDCAuditEventTagsAdded, rec.ARN, rec.URL, map[string]string{"count": fmt.Sprintf("%d", len(tags))})
|
||||
return nil
|
||||
}
|
||||
|
||||
// UntagOIDCProvider removes the named tags from the provider's tag set.
|
||||
func (m *IAMManager) UntagOIDCProvider(ctx context.Context, arn string, keys []string) error {
|
||||
if m.oidcProviderStore == nil {
|
||||
return fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
rec, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, k := range keys {
|
||||
delete(rec.Tags, k)
|
||||
}
|
||||
rec.UpdatedAt = time.Now().UTC()
|
||||
if err := m.oidcProviderStore.StoreProvider(ctx, m.getFilerAddress(), rec); err != nil {
|
||||
return err
|
||||
}
|
||||
m.emitOIDCAudit(ctx, OIDCAuditEventTagsRemoved, rec.ARN, rec.URL, map[string]string{"count": fmt.Sprintf("%d", len(keys))})
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateOIDCProviderRecord enforces the invariants AWS imposes on the
|
||||
// underlying CreateOpenIDConnectProvider call.
|
||||
func validateOIDCProviderRecord(rec *OIDCProviderRecord) error {
|
||||
if rec.URL == "" {
|
||||
return fmt.Errorf("Url is required")
|
||||
}
|
||||
if rec.ARN == "" {
|
||||
return fmt.Errorf("ARN is required")
|
||||
}
|
||||
if len(rec.ClientIDs) == 0 {
|
||||
return fmt.Errorf("ClientIDList must contain at least one entry")
|
||||
}
|
||||
if len(rec.ClientIDs) > 100 {
|
||||
return fmt.Errorf("ClientIDList must contain at most 100 entries")
|
||||
}
|
||||
if len(rec.Thumbprints) > 5 {
|
||||
return fmt.Errorf("ThumbprintList must contain at most 5 entries")
|
||||
}
|
||||
for _, tp := range rec.Thumbprints {
|
||||
if !isValidSHA1Thumbprint(tp) {
|
||||
return fmt.Errorf("invalid thumbprint %q: must be 40-character SHA-1 hex", tp)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// isValidSHA1Thumbprint returns true iff `s` is exactly 40 hex characters,
|
||||
// matching the SHA-1 digest format AWS expects.
|
||||
func isValidSHA1Thumbprint(s string) bool {
|
||||
if len(s) != 40 {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= '0' && r <= '9':
|
||||
case r >= 'a' && r <= 'f':
|
||||
case r >= 'A' && r <= 'F':
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// IAMConfig holds configuration for all IAM components
|
||||
@@ -43,6 +366,17 @@ type IAMConfig struct {
|
||||
|
||||
// Role store configuration
|
||||
Roles *RoleStoreConfig `json:"roleStore"`
|
||||
|
||||
// OIDCProviders configures the IAM-managed OIDC provider store. Optional;
|
||||
// if absent the manager defaults to an in-memory store hydrated from
|
||||
// STS.Providers at boot.
|
||||
OIDCProviders *OIDCProviderStoreConfig `json:"oidcProviderStore,omitempty"`
|
||||
}
|
||||
|
||||
// OIDCProviderStoreConfig holds OIDC provider store configuration.
|
||||
type OIDCProviderStoreConfig struct {
|
||||
StoreType string `json:"storeType"` // memory, filer
|
||||
StoreConfig map[string]interface{} `json:"storeConfig,omitempty"`
|
||||
}
|
||||
|
||||
// RoleStoreConfig holds role store configuration
|
||||
@@ -75,6 +409,12 @@ type RoleDefinition struct {
|
||||
|
||||
// Description is an optional description of the role
|
||||
Description string `json:"description,omitempty"`
|
||||
|
||||
// MaxSessionDuration is the upper bound (in seconds) on session length when
|
||||
// callers assume this role. Zero means "use the global STS default". When
|
||||
// set it must satisfy AWS bounds: 3600 ≤ MaxSessionDuration ≤ 43200.
|
||||
// Honoured by AssumeRole, AssumeRoleWithWebIdentity, AssumeRoleWithCredentials.
|
||||
MaxSessionDuration int64 `json:"maxSessionDuration,omitempty"`
|
||||
}
|
||||
|
||||
// ActionRequest represents a request to perform an action
|
||||
@@ -190,10 +530,213 @@ func (m *IAMManager) Initialize(config *IAMConfig, filerAddressProvider func() s
|
||||
}
|
||||
m.roleStore = roleStore
|
||||
|
||||
// Initialize OIDC provider store and hydrate from static configuration so
|
||||
// the read-only IAM API can return the same providers the STS service
|
||||
// already accepts. Mutations will land in Phase 2b.
|
||||
if err := m.initOIDCProviderStore(config); err != nil {
|
||||
return fmt.Errorf("failed to initialize OIDC provider store: %w", err)
|
||||
}
|
||||
|
||||
m.initialized = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// initOIDCProviderStore creates the OIDC provider store and seeds it from the
|
||||
// static STS provider configuration. The static path remains the bootstrap
|
||||
// source: each enabled OIDC entry under STS.Providers is mirrored as an
|
||||
// OIDCProviderRecord so the IAM API surfaces the same set the STS service
|
||||
// validates against.
|
||||
func (m *IAMManager) initOIDCProviderStore(config *IAMConfig) error {
|
||||
store, err := m.createOIDCProviderStore(config.OIDCProviders)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m.oidcProviderStore = store
|
||||
|
||||
if config.STS == nil {
|
||||
return nil
|
||||
}
|
||||
for _, pc := range config.STS.Providers {
|
||||
if pc == nil || !pc.Enabled || pc.Type != sts.ProviderTypeOIDC {
|
||||
continue
|
||||
}
|
||||
issuer, _ := pc.Config["issuer"].(string)
|
||||
if issuer == "" {
|
||||
glog.Warningf("OIDC provider %s in static config has empty issuer; skipping mirror to store", pc.Name)
|
||||
continue
|
||||
}
|
||||
accountID := ""
|
||||
if config.STS != nil {
|
||||
accountID = config.STS.AccountId
|
||||
}
|
||||
arn, err := DeriveOIDCProviderARN(accountID, issuer)
|
||||
if err != nil {
|
||||
glog.Warningf("derive ARN for static OIDC provider %s: %v", pc.Name, err)
|
||||
continue
|
||||
}
|
||||
clientIDs := extractClientIDs(pc.Config)
|
||||
ctx := context.Background()
|
||||
// Preserve CreatedAt across reboots when a persistent store already
|
||||
// has this provider — IAM's GetOpenIDConnectProvider response
|
||||
// shouldn't shift its CreateDate every time the server restarts.
|
||||
now := time.Now().UTC()
|
||||
createdAt := now
|
||||
if existing, err := store.GetProviderByARN(ctx, m.getFilerAddress(), arn); err == nil && existing != nil && !existing.CreatedAt.IsZero() {
|
||||
createdAt = existing.CreatedAt
|
||||
}
|
||||
rec := &OIDCProviderRecord{
|
||||
AccountID: accountID,
|
||||
ARN: arn,
|
||||
URL: issuer,
|
||||
ClientIDs: clientIDs,
|
||||
Thumbprints: extractStringList(pc.Config, "thumbprints"),
|
||||
AllowedPrincipalTagKeys: extractStringList(pc.Config, "allowedPrincipalTagKeys"),
|
||||
PolicyClaim: extractString(pc.Config, "policyClaim"),
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if err := store.StoreProvider(ctx, m.getFilerAddress(), rec); err != nil {
|
||||
glog.Warningf("mirror static OIDC provider %s into store: %v", pc.Name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// refreshOIDCProvidersBestEffort calls RefreshOIDCProvidersFromStore and
|
||||
// logs a warning on failure. The IAM API call has already succeeded by the
|
||||
// time we get here, so a refresh failure must not surface to the caller —
|
||||
// the worst case is that the local instance keeps the stale runtime view
|
||||
// until a peer's metadata-subscribe event triggers another refresh.
|
||||
func (m *IAMManager) refreshOIDCProvidersBestEffort(ctx context.Context, op, arn string) {
|
||||
if err := m.RefreshOIDCProvidersFromStore(ctx); err != nil {
|
||||
glog.Warningf("refresh OIDC providers after %s on %s: %v", op, arn, err)
|
||||
}
|
||||
}
|
||||
|
||||
// RefreshOIDCProvidersFromStore reloads every OIDCProviderRecord from the
|
||||
// configured store and pushes the resulting runtime providers into the STS
|
||||
// service so AssumeRoleWithWebIdentity sees the latest set without a
|
||||
// restart. Safe to call when no store is configured (returns nil) and when
|
||||
// the store is empty (clears the IAM-managed map). Records with empty URLs
|
||||
// or invalid configuration are logged and skipped so a single bad entry
|
||||
// does not stop the rest from refreshing.
|
||||
func (m *IAMManager) RefreshOIDCProvidersFromStore(ctx context.Context) error {
|
||||
if m.oidcProviderStore == nil || m.stsService == nil {
|
||||
return nil
|
||||
}
|
||||
records, err := m.oidcProviderStore.ListProviders(ctx, m.getFilerAddress())
|
||||
if err != nil {
|
||||
return fmt.Errorf("list OIDC providers: %w", err)
|
||||
}
|
||||
byIssuer := make(map[string][]sts.ScopedOIDCProvider, len(records))
|
||||
for _, rec := range records {
|
||||
if rec == nil || rec.URL == "" {
|
||||
continue
|
||||
}
|
||||
provider, err := buildOIDCProviderFromRecord(rec)
|
||||
if err != nil {
|
||||
glog.Warningf("skip refreshing OIDC provider %s: %v", rec.ARN, err)
|
||||
continue
|
||||
}
|
||||
// Multiple records may share an issuer when each is scoped to a
|
||||
// different account; STS picks the right one at validation time
|
||||
// based on the role being assumed. See lookupOIDCProviderForAccount.
|
||||
byIssuer[rec.URL] = append(byIssuer[rec.URL], sts.ScopedOIDCProvider{
|
||||
AccountID: rec.AccountID,
|
||||
Provider: provider,
|
||||
})
|
||||
}
|
||||
m.stsService.SetIAMManagedOIDCProviders(byIssuer)
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildOIDCProviderFromRecord turns a stored record into a runtime
|
||||
// OIDCProvider. The provider name is the ARN so re-registration is
|
||||
// idempotent and never collides with static-config entries.
|
||||
func buildOIDCProviderFromRecord(rec *OIDCProviderRecord) (*oidc.OIDCProvider, error) {
|
||||
if rec == nil {
|
||||
return nil, fmt.Errorf("record cannot be nil")
|
||||
}
|
||||
cfg := &oidc.OIDCConfig{
|
||||
Issuer: rec.URL,
|
||||
ClientIDs: append([]string(nil), rec.ClientIDs...),
|
||||
Thumbprints: append([]string(nil), rec.Thumbprints...),
|
||||
}
|
||||
provider := oidc.NewOIDCProvider(rec.ARN)
|
||||
if err := provider.Initialize(cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
// createOIDCProviderStore selects an OIDCProviderStore implementation. Defaults
|
||||
// to memory; "filer" requires a filerAddressProvider to be configured.
|
||||
func (m *IAMManager) createOIDCProviderStore(cfg *OIDCProviderStoreConfig) (OIDCProviderStore, error) {
|
||||
if cfg == nil || cfg.StoreType == "" || cfg.StoreType == "memory" {
|
||||
return NewMemoryOIDCProviderStore(), nil
|
||||
}
|
||||
if cfg.StoreType == "filer" {
|
||||
return NewFilerOIDCProviderStore(cfg.StoreConfig, m.filerAddressProvider), nil
|
||||
}
|
||||
return nil, fmt.Errorf("unsupported OIDC provider store type: %s", cfg.StoreType)
|
||||
}
|
||||
|
||||
// extractClientIDs reads a single clientId or a clientIds list from the
|
||||
// provider's static config map. Mirrors the OIDCConfig schema.
|
||||
func extractClientIDs(cfg map[string]interface{}) []string {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
if list, ok := cfg["clientIds"].([]interface{}); ok {
|
||||
out := make([]string, 0, len(list))
|
||||
for _, v := range list {
|
||||
if s, ok := v.(string); ok && s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
if len(out) > 0 {
|
||||
return out
|
||||
}
|
||||
}
|
||||
if id, ok := cfg["clientId"].(string); ok && id != "" {
|
||||
return []string{id}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractStringList reads a JSON string array out of the provider's static
|
||||
// config map and returns the non-empty entries. Returns nil when the key is
|
||||
// missing, the value is the wrong shape, or every entry is empty.
|
||||
func extractStringList(cfg map[string]interface{}, key string) []string {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
list, ok := cfg[key].([]interface{})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(list))
|
||||
for _, v := range list {
|
||||
if s, ok := v.(string); ok && s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// extractString reads a single string field from the provider's static
|
||||
// config map; missing or non-string values produce "".
|
||||
func extractString(cfg map[string]interface{}, key string) string {
|
||||
if cfg == nil {
|
||||
return ""
|
||||
}
|
||||
s, _ := cfg[key].(string)
|
||||
return s
|
||||
}
|
||||
|
||||
// getFilerAddress returns the current filer address using the provider function
|
||||
func (m *IAMManager) getFilerAddress() string {
|
||||
if m.filerAddressProvider != nil {
|
||||
@@ -272,6 +815,13 @@ func (m *IAMManager) CreateRole(ctx context.Context, filerAddress string, roleNa
|
||||
}
|
||||
}
|
||||
|
||||
// Validate per-role MaxSessionDuration if specified. AWS bounds: 1h..12h.
|
||||
if roleDef.MaxSessionDuration != 0 {
|
||||
if roleDef.MaxSessionDuration < 3600 || roleDef.MaxSessionDuration > 43200 {
|
||||
return fmt.Errorf("MaxSessionDuration must be between 3600 and 43200 seconds, got %d", roleDef.MaxSessionDuration)
|
||||
}
|
||||
}
|
||||
|
||||
// Store role definition
|
||||
return m.roleStore.StoreRole(ctx, "", roleName, roleDef)
|
||||
}
|
||||
@@ -315,6 +865,14 @@ func (m *IAMManager) AssumeRoleWithWebIdentity(ctx context.Context, request *sts
|
||||
return nil, fmt.Errorf("IAM manager not initialized")
|
||||
}
|
||||
|
||||
// Claim-based mode bypasses role lookup and trust policy entirely; the
|
||||
// STS service handles the policy resolution from the JWT itself. Account
|
||||
// scoping still applies but at the provider-resolution layer in Phase 3c
|
||||
// (we'll plug that in once a multi-account assume path lands).
|
||||
if sts.IsClaimBasedPolicyRoleArn(request.RoleArn) {
|
||||
return m.stsService.AssumeRoleWithWebIdentity(ctx, request)
|
||||
}
|
||||
|
||||
// Extract role name from ARN
|
||||
roleName := utils.ExtractRoleNameFromArn(request.RoleArn)
|
||||
|
||||
@@ -324,15 +882,103 @@ func (m *IAMManager) AssumeRoleWithWebIdentity(ctx context.Context, request *sts
|
||||
return nil, fmt.Errorf("role not found: %s", roleName)
|
||||
}
|
||||
|
||||
// Account scoping: when the role lives in account A, the OIDC provider
|
||||
// validating the token must be either global (AccountID="") or also live
|
||||
// in account A. Skip when we can't resolve account context; fall through
|
||||
// to the existing trust-policy enforcement.
|
||||
if err := m.enforceProviderAccountScope(ctx, request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Validate trust policy before allowing STS to assume the role
|
||||
if err := m.validateTrustPolicyForWebIdentity(ctx, roleDef, request.WebIdentityToken, request.DurationSeconds); err != nil {
|
||||
return nil, fmt.Errorf("trust policy validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Apply role-level MaxSessionDuration cap. The STS service still applies
|
||||
// the global MaxSessionLength and the source-token-expiry cap on top of
|
||||
// this; per-role takes precedence whenever it is the tightest bound.
|
||||
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration)
|
||||
|
||||
// Use STS service to assume the role
|
||||
return m.stsService.AssumeRoleWithWebIdentity(ctx, request)
|
||||
}
|
||||
|
||||
// enforceProviderAccountScope checks that the OIDC provider matching the
|
||||
// token's issuer is registered in either the role's account or as a global
|
||||
// (account-less) provider. Returns nil when no provider store is configured
|
||||
// (preserves the static-config-only path) or when the issuer is not known to
|
||||
// the store (the existing STS-layer issuer→provider map handles that case
|
||||
// during validation).
|
||||
func (m *IAMManager) enforceProviderAccountScope(ctx context.Context, request *sts.AssumeRoleWithWebIdentityRequest) error {
|
||||
if m.oidcProviderStore == nil {
|
||||
return nil
|
||||
}
|
||||
roleAccount := utils.ParseRoleARN(request.RoleArn).AccountID
|
||||
if roleAccount == "" {
|
||||
// Legacy ARN form (no account): nothing to enforce.
|
||||
return nil
|
||||
}
|
||||
issuer, err := extractIssuerFromJWT(request.WebIdentityToken)
|
||||
if err != nil {
|
||||
return nil // signature validation will reject, no need to fail twice
|
||||
}
|
||||
// Look for a provider that is either global or scoped to the role's
|
||||
// account. Multiple providers may share an issuer (e.g. one global plus
|
||||
// one per tenant), and GetProviderByIssuer returns the first match
|
||||
// arbitrarily — using it here would falsely reject a valid request
|
||||
// whenever the wrong record happens to come back first.
|
||||
if _, err := m.oidcProviderStore.GetProviderByIssuerAndAccount(ctx, m.getFilerAddress(), issuer, roleAccount); err == nil {
|
||||
return nil
|
||||
}
|
||||
// No allowed match. Distinguish "issuer entirely unknown" (let the STS
|
||||
// layer reject with the existing not-registered error) from "issuer is
|
||||
// registered but only in a different account" (surface a precise error
|
||||
// so the operator knows the call was cross-account).
|
||||
if other, err := m.oidcProviderStore.GetProviderByIssuer(ctx, m.getFilerAddress(), issuer); err == nil {
|
||||
return fmt.Errorf("OIDC provider for issuer %s is registered in account %s; cannot be used to assume a role in account %s", issuer, other.AccountID, roleAccount)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractIssuerFromJWT returns the iss claim of a JWT without verifying its
|
||||
// signature. Safe here because the caller still goes through full signature
|
||||
// + issuer validation in the STS service; this is purely for routing.
|
||||
func extractIssuerFromJWT(token string) (string, error) {
|
||||
parser := new(jwt.Parser)
|
||||
parsed, _, err := parser.ParseUnverified(token, jwt.MapClaims{})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
claims, ok := parsed.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("invalid claims")
|
||||
}
|
||||
iss, _ := claims["iss"].(string)
|
||||
if iss == "" {
|
||||
return "", fmt.Errorf("token has no iss claim")
|
||||
}
|
||||
return iss, nil
|
||||
}
|
||||
|
||||
// capDurationByRole returns the requested duration clamped to the role's
|
||||
// MaxSessionDuration. A nil requested duration is left nil so the STS
|
||||
// service's calculateSessionDuration applies the global default (typically
|
||||
// 1 hour) — substituting the role's max here would silently mint a 12h
|
||||
// session for any caller who omitted DurationSeconds, which AWS does not
|
||||
// do. The role-max upper bound still applies in the downstream cap chain
|
||||
// once the request has a concrete duration.
|
||||
func capDurationByRole(requested *int64, roleMax int64) *int64 {
|
||||
if roleMax <= 0 || requested == nil {
|
||||
return requested
|
||||
}
|
||||
if *requested > roleMax {
|
||||
v := roleMax
|
||||
return &v
|
||||
}
|
||||
return requested
|
||||
}
|
||||
|
||||
// AssumeRoleWithCredentials assumes a role using credentials (LDAP)
|
||||
func (m *IAMManager) AssumeRoleWithCredentials(ctx context.Context, request *sts.AssumeRoleWithCredentialsRequest) (*sts.AssumeRoleResponse, error) {
|
||||
if !m.initialized {
|
||||
@@ -353,6 +999,9 @@ func (m *IAMManager) AssumeRoleWithCredentials(ctx context.Context, request *sts
|
||||
return nil, fmt.Errorf("trust policy validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Apply role-level MaxSessionDuration cap.
|
||||
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration)
|
||||
|
||||
// Use STS service to assume the role
|
||||
return m.stsService.AssumeRoleWithCredentials(ctx, request)
|
||||
}
|
||||
@@ -387,6 +1036,18 @@ func (m *IAMManager) IsActionAllowed(ctx context.Context, request *ActionRequest
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("invalid session: %w", err)
|
||||
}
|
||||
// Reject sessions whose JTI has been added to the revocation
|
||||
// blocklist. SessionId == JTI for STS-issued tokens; this lookup
|
||||
// is hot, so the store implementation must be O(1).
|
||||
if sessionInfo != nil && sessionInfo.SessionId != "" {
|
||||
revoked, rerr := m.IsSessionRevoked(ctx, sessionInfo.SessionId)
|
||||
if rerr != nil {
|
||||
return false, fmt.Errorf("revocation check failed: %w", rerr)
|
||||
}
|
||||
if revoked {
|
||||
return false, fmt.Errorf("session has been revoked")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -450,13 +1111,20 @@ func (m *IAMManager) IsActionAllowed(ctx context.Context, request *ActionRequest
|
||||
|
||||
var baseResult *policy.EvaluationResult
|
||||
var err error
|
||||
subjectPolicyCount := 0
|
||||
// hasManagedSubject is true once we've resolved the principal to a registered
|
||||
// IAM user or role (or the caller has supplied PolicyNames directly). For a
|
||||
// managed subject, "no matching statement" must deny — the DefaultEffect=Allow
|
||||
// fallback is only meant for the unmanaged zero-config startup case.
|
||||
hasManagedSubject := false
|
||||
|
||||
if isAdmin {
|
||||
// Admin always has base access allowed
|
||||
baseResult = &policy.EvaluationResult{Effect: policy.EffectAllow}
|
||||
} else {
|
||||
policies := request.PolicyNames
|
||||
if len(policies) > 0 {
|
||||
hasManagedSubject = true
|
||||
}
|
||||
if len(policies) == 0 {
|
||||
// Extract role name from principal ARN
|
||||
roleName := utils.ExtractRoleNameFromPrincipal(request.Principal)
|
||||
@@ -472,6 +1140,7 @@ func (m *IAMManager) IsActionAllowed(ctx context.Context, request *ActionRequest
|
||||
if err != nil || user == nil {
|
||||
return false, fmt.Errorf("user not found for principal: %s (user=%s)", request.Principal, userName)
|
||||
}
|
||||
hasManagedSubject = true
|
||||
policies = user.GetPolicyNames()
|
||||
} else {
|
||||
// Get role definition
|
||||
@@ -480,11 +1149,10 @@ func (m *IAMManager) IsActionAllowed(ctx context.Context, request *ActionRequest
|
||||
return false, fmt.Errorf("role not found: %s", roleName)
|
||||
}
|
||||
|
||||
hasManagedSubject = true
|
||||
policies = roleDef.AttachedPolicies
|
||||
}
|
||||
}
|
||||
subjectPolicyCount = len(policies)
|
||||
|
||||
if bucketPolicyName != "" {
|
||||
// Enforce an upper bound on the number of policies to avoid excessive allocations
|
||||
if len(policies) >= maxPoliciesForEvaluation {
|
||||
@@ -508,10 +1176,11 @@ func (m *IAMManager) IsActionAllowed(ctx context.Context, request *ActionRequest
|
||||
}
|
||||
|
||||
// Zero-config IAM uses DefaultEffect=Allow to preserve open-by-default behavior
|
||||
// for requests without any subject policies. Once a user or role has attached
|
||||
// policies, "no matching statement" must fall back to deny so the attachment
|
||||
// actually scopes access.
|
||||
if subjectPolicyCount > 0 && len(baseResult.MatchingStatements) == 0 {
|
||||
// for requests without any subject policies. Once we resolve the principal to
|
||||
// a registered IAM user or role (or the caller hands us policy names),
|
||||
// "no matching statement" must fall back to deny — otherwise a freshly
|
||||
// created user with zero policies would inherit full access.
|
||||
if hasManagedSubject && len(baseResult.MatchingStatements) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type fakeUserStore struct {
|
||||
users map[string]*iam_pb.Identity
|
||||
}
|
||||
|
||||
func (f *fakeUserStore) GetUser(_ context.Context, name string) (*iam_pb.Identity, error) {
|
||||
if u, ok := f.users[name]; ok {
|
||||
return u, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// TestIsActionAllowed_RegisteredUserWithoutPoliciesIsDenied is a regression test
|
||||
// for a security issue where a user created via the S3 IAM API with no policies
|
||||
// attached was granted access to every S3 action. The default-allow path was
|
||||
// intended for unmanaged zero-config startup, not for explicitly registered IAM
|
||||
// users with an empty policy set.
|
||||
func TestIsActionAllowed_RegisteredUserWithoutPoliciesIsDenied(t *testing.T) {
|
||||
manager := NewIAMManager()
|
||||
require.NoError(t, manager.Initialize(&IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test-sts",
|
||||
SigningKey: []byte("test-signing-key-32-characters-long"),
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{
|
||||
// Reproduce the zero-config setup: with no IAM config file, the
|
||||
// loader picks DefaultEffect=Allow for in-memory mode.
|
||||
DefaultEffect: string(policy.EffectAllow),
|
||||
StoreType: sts.StoreTypeMemory,
|
||||
},
|
||||
Roles: &RoleStoreConfig{StoreType: sts.StoreTypeMemory},
|
||||
}, func() string { return "localhost:8888" }))
|
||||
|
||||
manager.SetUserStore(&fakeUserStore{users: map[string]*iam_pb.Identity{
|
||||
"newuser": {Name: "newuser"}, // no PolicyNames, no Actions
|
||||
}})
|
||||
|
||||
allowed, err := manager.IsActionAllowed(context.Background(), &ActionRequest{
|
||||
Principal: "arn:aws:iam::seaweedfs:user/newuser",
|
||||
Action: "s3:DeleteBucket",
|
||||
Resource: "arn:aws:s3:::any-bucket",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, allowed, "registered user with no policies must not get default-allow access")
|
||||
}
|
||||
|
||||
// TestIsActionAllowed_RegisteredRoleWithoutPoliciesIsDenied is the role-side
|
||||
// counterpart of the registered-user regression: a managed role that exists
|
||||
// but has zero AttachedPolicies must not inherit full access from the
|
||||
// zero-config DefaultEffect=Allow fallback. Coderabbit flagged this as an
|
||||
// uncovered branch of the same fix on PR #9317.
|
||||
func TestIsActionAllowed_RegisteredRoleWithoutPoliciesIsDenied(t *testing.T) {
|
||||
manager := NewIAMManager()
|
||||
require.NoError(t, manager.Initialize(&IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test-sts",
|
||||
SigningKey: []byte("test-signing-key-32-characters-long"),
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{
|
||||
DefaultEffect: string(policy.EffectAllow),
|
||||
StoreType: sts.StoreTypeMemory,
|
||||
},
|
||||
Roles: &RoleStoreConfig{StoreType: sts.StoreTypeMemory},
|
||||
}, func() string { return "localhost:8888" }))
|
||||
|
||||
ctx := context.Background()
|
||||
require.NoError(t, manager.CreateRole(ctx, "", "EmptyRole", &RoleDefinition{
|
||||
RoleName: "EmptyRole",
|
||||
RoleArn: "arn:aws:iam::seaweedfs:role/EmptyRole",
|
||||
AttachedPolicies: nil, // explicit: managed role with no policies attached
|
||||
}))
|
||||
|
||||
allowed, err := manager.IsActionAllowed(ctx, &ActionRequest{
|
||||
// Use the assumed-role principal form the STS path produces. The
|
||||
// IAM manager extracts role name via ExtractRoleNameFromPrincipal,
|
||||
// finds the role definition, and must deny because AttachedPolicies
|
||||
// is empty even though DefaultEffect is Allow.
|
||||
Principal: "arn:aws:sts::seaweedfs:assumed-role/EmptyRole/some-session",
|
||||
Action: "s3:DeleteBucket",
|
||||
Resource: "arn:aws:s3:::any-bucket",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, allowed, "registered role with no attached policies must not get default-allow access")
|
||||
}
|
||||
|
||||
// TestIsActionAllowed_RegisteredUserWithNonMatchingPolicyIsDenied covers the
|
||||
// adjacent case: the user has policies attached, but none of the policy
|
||||
// statements match the requested action/resource. The DefaultEffect=Allow
|
||||
// fallback must not silently grant access when an attached policy simply
|
||||
// does not say anything about this action.
|
||||
func TestIsActionAllowed_RegisteredUserWithNonMatchingPolicyIsDenied(t *testing.T) {
|
||||
manager := NewIAMManager()
|
||||
require.NoError(t, manager.Initialize(&IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test-sts",
|
||||
SigningKey: []byte("test-signing-key-32-characters-long"),
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{
|
||||
DefaultEffect: string(policy.EffectAllow),
|
||||
StoreType: sts.StoreTypeMemory,
|
||||
},
|
||||
Roles: &RoleStoreConfig{StoreType: sts.StoreTypeMemory},
|
||||
}, func() string { return "localhost:8888" }))
|
||||
|
||||
ctx := context.Background()
|
||||
require.NoError(t, manager.CreatePolicy(ctx, "", "ReadOnlyOneBucket", &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:GetObject"},
|
||||
Resource: []string{"arn:aws:s3:::reports/*"},
|
||||
}},
|
||||
}))
|
||||
|
||||
manager.SetUserStore(&fakeUserStore{users: map[string]*iam_pb.Identity{
|
||||
"alice": {Name: "alice", PolicyNames: []string{"ReadOnlyOneBucket"}},
|
||||
}})
|
||||
|
||||
allowed, err := manager.IsActionAllowed(ctx, &ActionRequest{
|
||||
Principal: "arn:aws:iam::seaweedfs:user/alice",
|
||||
Action: "s3:DeleteBucket",
|
||||
Resource: "arn:aws:s3:::other-bucket",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, allowed, "action outside the user's attached policy must be denied")
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// OIDCProviderAuditEventType enumerates the lifecycle events emitted when an
|
||||
// IAM-managed OIDC provider record is mutated. Use-events (every successful
|
||||
// token validation) are intentionally not emitted by the lifecycle path:
|
||||
// they're too hot to stream into a filer-backed sink without spikes. A
|
||||
// future PR can add a sampled-use sink behind an explicit opt-in flag.
|
||||
type OIDCProviderAuditEventType string
|
||||
|
||||
const (
|
||||
OIDCAuditEventCreated OIDCProviderAuditEventType = "Create"
|
||||
OIDCAuditEventDeleted OIDCProviderAuditEventType = "Delete"
|
||||
OIDCAuditEventClientIDAdded OIDCProviderAuditEventType = "AddClientID"
|
||||
OIDCAuditEventClientIDRemoved OIDCProviderAuditEventType = "RemoveClientID"
|
||||
OIDCAuditEventThumbprintsSet OIDCProviderAuditEventType = "UpdateThumbprints"
|
||||
OIDCAuditEventTagsAdded OIDCProviderAuditEventType = "Tag"
|
||||
OIDCAuditEventTagsRemoved OIDCProviderAuditEventType = "Untag"
|
||||
)
|
||||
|
||||
// OIDCProviderAuditEvent is the payload emitted for each lifecycle event.
|
||||
type OIDCProviderAuditEvent struct {
|
||||
Type OIDCProviderAuditEventType `json:"type"`
|
||||
ARN string `json:"arn"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Detail map[string]string `json:"detail,omitempty"`
|
||||
OccurredAt time.Time `json:"occurredAt"`
|
||||
}
|
||||
|
||||
// OIDCProviderAuditSink consumes lifecycle events. Implementations must be
|
||||
// safe for concurrent use; emit happens with the IAM manager's mutation lock
|
||||
// held, so a slow sink slows the IAM API.
|
||||
type OIDCProviderAuditSink interface {
|
||||
Emit(ctx context.Context, event *OIDCProviderAuditEvent) error
|
||||
}
|
||||
|
||||
// GlogAuditSink writes one structured log line per event. Always-on default
|
||||
// when an explicit sink isn't configured — events still appear in stdout/the
|
||||
// log aggregator, just not in a queryable record.
|
||||
type GlogAuditSink struct{}
|
||||
|
||||
func (GlogAuditSink) Emit(_ context.Context, event *OIDCProviderAuditEvent) error {
|
||||
if event == nil {
|
||||
return nil
|
||||
}
|
||||
data, err := json.Marshal(event)
|
||||
if err != nil {
|
||||
glog.V(0).Infof("oidc-audit: %s arn=%s err-marshal=%v", event.Type, event.ARN, err)
|
||||
return nil
|
||||
}
|
||||
glog.V(0).Infof("oidc-audit: %s", string(data))
|
||||
return nil
|
||||
}
|
||||
|
||||
// MemoryAuditSink keeps events in process memory for tests and short-lived
|
||||
// inspection. Not durable; drop entries by reading from Events() and
|
||||
// discarding.
|
||||
type MemoryAuditSink struct {
|
||||
mu sync.Mutex
|
||||
events []*OIDCProviderAuditEvent
|
||||
}
|
||||
|
||||
func NewMemoryAuditSink() *MemoryAuditSink {
|
||||
return &MemoryAuditSink{}
|
||||
}
|
||||
|
||||
func (m *MemoryAuditSink) Emit(_ context.Context, event *OIDCProviderAuditEvent) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
cp := *event
|
||||
m.events = append(m.events, &cp)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Events returns a copy of the captured event log so tests can assert.
|
||||
func (m *MemoryAuditSink) Events() []*OIDCProviderAuditEvent {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
out := make([]*OIDCProviderAuditEvent, len(m.events))
|
||||
copy(out, m.events)
|
||||
return out
|
||||
}
|
||||
|
||||
// FilerAuditSink appends event records as separate files under a filer
|
||||
// directory. Each event is its own file so concurrent writers don't conflict;
|
||||
// the filename is `<unixnano>-<type>-<arnhash>.json`. For higher volumes,
|
||||
// switch to an append-only journal — the contract is just `Emit`.
|
||||
type FilerAuditSink struct {
|
||||
grpcDialOption grpc.DialOption
|
||||
basePath string
|
||||
filerAddressProvider func() string
|
||||
}
|
||||
|
||||
// NewFilerAuditSink returns a filer-backed sink. Default basePath
|
||||
// `/etc/iam/audit/oidc-providers` keeps audit records out of the active
|
||||
// IAM data directories.
|
||||
func NewFilerAuditSink(config map[string]interface{}, filerAddressProvider func() string) *FilerAuditSink {
|
||||
sink := &FilerAuditSink{
|
||||
basePath: "/etc/iam/audit/oidc-providers",
|
||||
filerAddressProvider: filerAddressProvider,
|
||||
}
|
||||
if config != nil {
|
||||
if bp, ok := config["basePath"].(string); ok && bp != "" {
|
||||
sink.basePath = strings.TrimSuffix(bp, "/")
|
||||
}
|
||||
}
|
||||
return sink
|
||||
}
|
||||
|
||||
func (f *FilerAuditSink) resolveFilerAddress() string {
|
||||
if f.filerAddressProvider != nil {
|
||||
return f.filerAddressProvider()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (f *FilerAuditSink) Emit(ctx context.Context, event *OIDCProviderAuditEvent) error {
|
||||
addr := f.resolveFilerAddress()
|
||||
if addr == "" {
|
||||
return fmt.Errorf("filer address not available")
|
||||
}
|
||||
if event == nil {
|
||||
return nil
|
||||
}
|
||||
if event.OccurredAt.IsZero() {
|
||||
event.OccurredAt = time.Now().UTC()
|
||||
}
|
||||
data, err := json.MarshalIndent(event, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal audit event: %v", err)
|
||||
}
|
||||
// Filename: <unixnano>-<type>-<arnhash>.json. Two events at the same
|
||||
// nano against the same ARN+type are vanishingly rare, but two events
|
||||
// at the same nano against different ARNs are perfectly plausible
|
||||
// (audit-via-batch script). The ARN hash gives us an effectively-
|
||||
// collision-free name without leaking the ARN into the filer path.
|
||||
arnSum := sha1.Sum([]byte(event.ARN))
|
||||
name := fmt.Sprintf("%d-%s-%s.json", event.OccurredAt.UnixNano(), event.Type, hex.EncodeToString(arnSum[:8]))
|
||||
occurredAt := event.OccurredAt.Unix()
|
||||
return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(addr), f.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
_, err := client.CreateEntry(ctx, &filer_pb.CreateEntryRequest{
|
||||
Directory: f.basePath,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: name,
|
||||
IsDirectory: false,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
// Reflect the event's occurrence time so file metadata
|
||||
// matches the audit record itself, not the filer write.
|
||||
Mtime: occurredAt,
|
||||
Crtime: occurredAt,
|
||||
FileMode: uint32(0o600),
|
||||
},
|
||||
Content: data,
|
||||
},
|
||||
})
|
||||
return err
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
)
|
||||
|
||||
func newAuditableManager(t *testing.T) (*IAMManager, *MemoryAuditSink) {
|
||||
t.Helper()
|
||||
mgr := NewIAMManager()
|
||||
sink := NewMemoryAuditSink()
|
||||
cfg := &IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test-sts",
|
||||
SigningKey: []byte("test-signing-key-32-characters-long"),
|
||||
AccountId: "111122223333",
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{DefaultEffect: "Deny", StoreType: "memory"},
|
||||
Roles: &RoleStoreConfig{StoreType: "memory"},
|
||||
}
|
||||
if err := mgr.Initialize(cfg, func() string { return "localhost:8888" }); err != nil {
|
||||
t.Fatalf("Initialize: %v", err)
|
||||
}
|
||||
mgr.SetOIDCProviderAuditSink(sink)
|
||||
return mgr, sink
|
||||
}
|
||||
|
||||
func TestOIDCAuditLifecycleEventsAreEmitted(t *testing.T) {
|
||||
mgr, sink := newAuditableManager(t)
|
||||
ctx := context.Background()
|
||||
|
||||
rec := &OIDCProviderRecord{
|
||||
AccountID: "111122223333",
|
||||
ARN: "arn:aws:iam::111122223333:oidc-provider/idp.example",
|
||||
URL: "https://idp.example",
|
||||
ClientIDs: []string{"x"},
|
||||
}
|
||||
if err := mgr.CreateOIDCProvider(ctx, rec); err != nil {
|
||||
t.Fatalf("Create: %v", err)
|
||||
}
|
||||
if err := mgr.AddClientIDToOIDCProvider(ctx, rec.ARN, "y"); err != nil {
|
||||
t.Fatalf("AddClientID: %v", err)
|
||||
}
|
||||
if err := mgr.RemoveClientIDFromOIDCProvider(ctx, rec.ARN, "y"); err != nil {
|
||||
t.Fatalf("RemoveClientID: %v", err)
|
||||
}
|
||||
if err := mgr.UpdateOIDCProviderThumbprints(ctx, rec.ARN, []string{"0000000000000000000000000000000000000000"}); err != nil {
|
||||
t.Fatalf("UpdateThumbprints: %v", err)
|
||||
}
|
||||
if err := mgr.TagOIDCProvider(ctx, rec.ARN, map[string]string{"team": "infra"}); err != nil {
|
||||
t.Fatalf("Tag: %v", err)
|
||||
}
|
||||
if err := mgr.UntagOIDCProvider(ctx, rec.ARN, []string{"team"}); err != nil {
|
||||
t.Fatalf("Untag: %v", err)
|
||||
}
|
||||
if err := mgr.DeleteOIDCProvider(ctx, rec.ARN); err != nil {
|
||||
t.Fatalf("Delete: %v", err)
|
||||
}
|
||||
|
||||
want := []OIDCProviderAuditEventType{
|
||||
OIDCAuditEventCreated,
|
||||
OIDCAuditEventClientIDAdded,
|
||||
OIDCAuditEventClientIDRemoved,
|
||||
OIDCAuditEventThumbprintsSet,
|
||||
OIDCAuditEventTagsAdded,
|
||||
OIDCAuditEventTagsRemoved,
|
||||
OIDCAuditEventDeleted,
|
||||
}
|
||||
events := sink.Events()
|
||||
if len(events) != len(want) {
|
||||
t.Fatalf("expected %d events, got %d (%+v)", len(want), len(events), events)
|
||||
}
|
||||
for i, e := range events {
|
||||
if e.Type != want[i] {
|
||||
t.Errorf("event %d: type=%s want=%s", i, e.Type, want[i])
|
||||
}
|
||||
if e.ARN != rec.ARN {
|
||||
t.Errorf("event %d: ARN=%s want=%s", i, e.ARN, rec.ARN)
|
||||
}
|
||||
if e.OccurredAt.IsZero() {
|
||||
t.Errorf("event %d has zero OccurredAt", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCAuditDefaultsToGlogSink(t *testing.T) {
|
||||
// No SetOIDCProviderAuditSink call — should default to glog and not panic.
|
||||
mgr, _ := newAuditableManager(t)
|
||||
mgr.SetOIDCProviderAuditSink(nil)
|
||||
rec := &OIDCProviderRecord{
|
||||
AccountID: "111122223333",
|
||||
ARN: "arn:aws:iam::111122223333:oidc-provider/idp.example",
|
||||
URL: "https://idp.example",
|
||||
ClientIDs: []string{"x"},
|
||||
}
|
||||
if err := mgr.CreateOIDCProvider(context.Background(), rec); err != nil {
|
||||
t.Fatalf("Create with default sink: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
)
|
||||
|
||||
func TestStaticConfigSeedsProviderStore(t *testing.T) {
|
||||
mgr := NewIAMManager()
|
||||
cfg := &IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test-sts",
|
||||
SigningKey: []byte("test-signing-key-32-characters-long"),
|
||||
AccountId: "111122223333",
|
||||
Providers: []*sts.ProviderConfig{
|
||||
{
|
||||
Name: "google",
|
||||
Type: sts.ProviderTypeOIDC,
|
||||
Enabled: true,
|
||||
Config: map[string]interface{}{
|
||||
"issuer": "https://accounts.google.com",
|
||||
"clientId": "1234.apps.googleusercontent.com",
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "github-actions",
|
||||
Type: sts.ProviderTypeOIDC,
|
||||
Enabled: true,
|
||||
Config: map[string]interface{}{
|
||||
"issuer": "https://token.actions.githubusercontent.com",
|
||||
"clientId": "sts.amazonaws.com",
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "disabled-google",
|
||||
Type: sts.ProviderTypeOIDC,
|
||||
Enabled: false,
|
||||
Config: map[string]interface{}{
|
||||
"issuer": "https://accounts.disabled.example",
|
||||
"clientId": "x",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{DefaultEffect: "Deny", StoreType: "memory"},
|
||||
Roles: &RoleStoreConfig{StoreType: "memory"},
|
||||
}
|
||||
if err := mgr.Initialize(cfg, func() string { return "localhost:8888" }); err != nil {
|
||||
t.Fatalf("Initialize: %v", err)
|
||||
}
|
||||
|
||||
store := mgr.GetOIDCProviderStore()
|
||||
if store == nil {
|
||||
t.Fatal("expected store to be initialized")
|
||||
}
|
||||
|
||||
got, err := mgr.ListOIDCProviders(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("ListOIDCProviders: %v", err)
|
||||
}
|
||||
// Disabled providers must not be mirrored.
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("expected 2 providers, got %d (%v)", len(got), got)
|
||||
}
|
||||
|
||||
byArn := map[string]*OIDCProviderRecord{}
|
||||
for _, r := range got {
|
||||
byArn[r.ARN] = r
|
||||
}
|
||||
|
||||
googleARN := "arn:aws:iam::111122223333:oidc-provider/accounts.google.com"
|
||||
g, ok := byArn[googleARN]
|
||||
if !ok {
|
||||
t.Fatalf("missing google ARN; have %v", byArn)
|
||||
}
|
||||
if len(g.ClientIDs) != 1 || g.ClientIDs[0] != "1234.apps.googleusercontent.com" {
|
||||
t.Fatalf("google clientIds wrong: %v", g.ClientIDs)
|
||||
}
|
||||
|
||||
ghARN := "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com"
|
||||
gh, ok := byArn[ghARN]
|
||||
if !ok {
|
||||
t.Fatalf("missing github-actions ARN; have %v", byArn)
|
||||
}
|
||||
if len(gh.ClientIDs) != 1 || gh.ClientIDs[0] != "sts.amazonaws.com" {
|
||||
t.Fatalf("github clientIds wrong: %v", gh.ClientIDs)
|
||||
}
|
||||
|
||||
// Spot-check the IAM read path returns the same record.
|
||||
rec, err := mgr.GetOIDCProvider(context.Background(), googleARN)
|
||||
if err != nil {
|
||||
t.Fatalf("GetOIDCProvider: %v", err)
|
||||
}
|
||||
if rec.URL != "https://accounts.google.com" {
|
||||
t.Fatalf("URL mismatch: %s", rec.URL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaticConfigMirrorsThumbprintsAndAdvancedFields(t *testing.T) {
|
||||
// Static config sets thumbprints, AllowedPrincipalTagKeys, and PolicyClaim;
|
||||
// the mirror into the IAM-managed store must carry all three. Without it,
|
||||
// the next RefreshOIDCProvidersFromStore rebuilds a runtime provider that
|
||||
// drops thumbprint pinning and silently disables claim-based policies and
|
||||
// principal-tag passthrough — and because IAM-managed entries take
|
||||
// precedence over the static-config map, the bootstrap provider gets
|
||||
// shadowed by this weaker rebuild.
|
||||
mgr := NewIAMManager()
|
||||
cfg := &IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test-sts",
|
||||
SigningKey: []byte("test-signing-key-32-characters-long"),
|
||||
AccountId: "111122223333",
|
||||
Providers: []*sts.ProviderConfig{
|
||||
{
|
||||
Name: "github-actions",
|
||||
Type: sts.ProviderTypeOIDC,
|
||||
Enabled: true,
|
||||
Config: map[string]interface{}{
|
||||
"issuer": "https://token.actions.githubusercontent.com",
|
||||
"clientId": "sts.amazonaws.com",
|
||||
"thumbprints": []interface{}{"6938fd4d98bab03faadb97b34396831e3780aea1"},
|
||||
"allowedPrincipalTagKeys": []interface{}{"team", "env"},
|
||||
"policyClaim": "policies",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{DefaultEffect: "Deny", StoreType: "memory"},
|
||||
Roles: &RoleStoreConfig{StoreType: "memory"},
|
||||
}
|
||||
if err := mgr.Initialize(cfg, func() string { return "localhost:8888" }); err != nil {
|
||||
t.Fatalf("Initialize: %v", err)
|
||||
}
|
||||
|
||||
rec, err := mgr.GetOIDCProvider(context.Background(), "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com")
|
||||
if err != nil {
|
||||
t.Fatalf("GetOIDCProvider: %v", err)
|
||||
}
|
||||
if got, want := rec.Thumbprints, []string{"6938fd4d98bab03faadb97b34396831e3780aea1"}; !equalStrings(got, want) {
|
||||
t.Fatalf("thumbprints mismatch: got %v want %v", got, want)
|
||||
}
|
||||
if got, want := rec.AllowedPrincipalTagKeys, []string{"team", "env"}; !equalStrings(got, want) {
|
||||
t.Fatalf("allowedPrincipalTagKeys mismatch: got %v want %v", got, want)
|
||||
}
|
||||
if rec.PolicyClaim != "policies" {
|
||||
t.Fatalf("policyClaim mismatch: got %q want %q", rec.PolicyClaim, "policies")
|
||||
}
|
||||
}
|
||||
|
||||
func equalStrings(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func TestStoreNotConfiguredReturnsClearError(t *testing.T) {
|
||||
mgr := NewIAMManager()
|
||||
if _, err := mgr.GetOIDCProvider(context.Background(), "arn:..."); err == nil {
|
||||
t.Fatal("expected error when store not configured")
|
||||
}
|
||||
if _, err := mgr.ListOIDCProviders(context.Background()); err == nil {
|
||||
t.Fatal("expected error when store not configured")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// Sentinel errors returned by the IAM manager and OIDCProviderStore. Callers
|
||||
// in the s3api layer use errors.Is rather than substring-matching the
|
||||
// formatted message, so the message can be edited freely without changing
|
||||
// the IAM error code surfaced to the API caller.
|
||||
var (
|
||||
ErrOIDCProviderNotFound = errors.New("OIDC provider not found")
|
||||
ErrOIDCProviderAlreadyExists = errors.New("OIDC provider already exists")
|
||||
)
|
||||
|
||||
// OIDCProviderRecord is the persisted, IAM-managed view of an OIDC identity
|
||||
// provider. It is the source of truth consulted at AssumeRoleWithWebIdentity
|
||||
// time. Static configuration entries are loaded into this same store at
|
||||
// startup so the resolution path is uniform.
|
||||
type OIDCProviderRecord struct {
|
||||
// AccountID scopes the record. Empty means "global" — usable from any
|
||||
// account. Non-empty records are only resolvable when the assuming
|
||||
// caller's RoleArn lives in the same account. Phase 2a leaves this
|
||||
// field unenforced; Phase 3c lights up the cross-account check.
|
||||
AccountID string `json:"accountId,omitempty"`
|
||||
|
||||
// ARN is the canonical IAM identifier for the provider:
|
||||
// arn:aws:iam::<account>:oidc-provider/<host>/<path>.
|
||||
ARN string `json:"arn"`
|
||||
|
||||
// URL is the issuer URL (no trailing slash), e.g.
|
||||
// https://token.actions.githubusercontent.com.
|
||||
URL string `json:"url"`
|
||||
|
||||
// ClientIDs are the audiences AWS calls "client IDs". A token's `aud` or
|
||||
// `azp` must match one of these for the token to be accepted.
|
||||
ClientIDs []string `json:"clientIds,omitempty"`
|
||||
|
||||
// Thumbprints are SHA-1 hex digests of the IDP's TLS certificate, matching
|
||||
// the AWS-compatible thumbprint algorithm. Used at JWKS-fetch time when
|
||||
// non-empty; an empty list means "trust the system root store".
|
||||
Thumbprints []string `json:"thumbprints,omitempty"`
|
||||
|
||||
// AllowedPrincipalTagKeys is the per-provider ABAC allowlist for the
|
||||
// `https://aws.amazon.com/tags/principal_tags` claim namespace. Empty
|
||||
// means no tags are surfaced from this provider.
|
||||
AllowedPrincipalTagKeys []string `json:"allowedPrincipalTagKeys,omitempty"`
|
||||
|
||||
// PolicyClaim, when non-empty, enables claim-based policy mode for this
|
||||
// provider: tokens whose RoleArn matches the configured sentinel will
|
||||
// derive their effective policies from this JWT claim.
|
||||
PolicyClaim string `json:"policyClaim,omitempty"`
|
||||
|
||||
// Tags is the AWS-style tag set attached to the IAM resource itself
|
||||
// (audit/inventory metadata, not propagated into sessions).
|
||||
Tags map[string]string `json:"tags,omitempty"`
|
||||
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// OIDCProviderStore stores OIDCProviderRecord entries. Implementations are
|
||||
// expected to be safe for concurrent use.
|
||||
type OIDCProviderStore interface {
|
||||
StoreProvider(ctx context.Context, filerAddress string, record *OIDCProviderRecord) error
|
||||
GetProviderByARN(ctx context.Context, filerAddress string, arn string) (*OIDCProviderRecord, error)
|
||||
GetProviderByIssuer(ctx context.Context, filerAddress string, issuer string) (*OIDCProviderRecord, error)
|
||||
GetProviderByIssuerAndAccount(ctx context.Context, filerAddress string, issuer, accountID string) (*OIDCProviderRecord, error)
|
||||
ListProviders(ctx context.Context, filerAddress string) ([]*OIDCProviderRecord, error)
|
||||
DeleteProvider(ctx context.Context, filerAddress string, arn string) error
|
||||
}
|
||||
|
||||
// MemoryOIDCProviderStore is a process-local store, suitable for tests and
|
||||
// single-node deployments. It also acts as the in-memory cache hydrated from
|
||||
// static config at boot.
|
||||
type MemoryOIDCProviderStore struct {
|
||||
mu sync.RWMutex
|
||||
providers map[string]*OIDCProviderRecord // keyed by ARN
|
||||
}
|
||||
|
||||
// NewMemoryOIDCProviderStore creates an empty in-memory store.
|
||||
func NewMemoryOIDCProviderStore() *MemoryOIDCProviderStore {
|
||||
return &MemoryOIDCProviderStore{providers: make(map[string]*OIDCProviderRecord)}
|
||||
}
|
||||
|
||||
// StoreProvider replaces any existing record with the same ARN.
|
||||
func (m *MemoryOIDCProviderStore) StoreProvider(ctx context.Context, _ string, record *OIDCProviderRecord) error {
|
||||
if record == nil {
|
||||
return fmt.Errorf("record cannot be nil")
|
||||
}
|
||||
if record.ARN == "" {
|
||||
return fmt.Errorf("record.ARN is required")
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.providers[record.ARN] = copyOIDCProviderRecord(record)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetProviderByARN returns the record with the given ARN, or an error if absent.
|
||||
func (m *MemoryOIDCProviderStore) GetProviderByARN(ctx context.Context, _ string, arn string) (*OIDCProviderRecord, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
rec, ok := m.providers[arn]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: %s", ErrOIDCProviderNotFound, arn)
|
||||
}
|
||||
return copyOIDCProviderRecord(rec), nil
|
||||
}
|
||||
|
||||
// GetProviderByIssuer scans for the first record whose URL matches `issuer`.
|
||||
// Comparison strips trailing slashes and is case-insensitive on host.
|
||||
func (m *MemoryOIDCProviderStore) GetProviderByIssuer(ctx context.Context, _ string, issuer string) (*OIDCProviderRecord, error) {
|
||||
want := normalizeIssuer(issuer)
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
for _, rec := range m.providers {
|
||||
if normalizeIssuer(rec.URL) == want {
|
||||
return copyOIDCProviderRecord(rec), nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("no OIDC provider registered for issuer: %s", issuer)
|
||||
}
|
||||
|
||||
// GetProviderByIssuerAndAccount returns the record matching `issuer` whose
|
||||
// AccountID is empty (global) or equals `accountID`. AWS-style account
|
||||
// scoping: cross-account references must go through a shared/global
|
||||
// provider, which is why an empty AccountID is treated as a wildcard.
|
||||
//
|
||||
// `accountID` may itself be empty when the caller has no specific account
|
||||
// context (e.g. claim-based mode); in that case any registered provider
|
||||
// matching the issuer is acceptable.
|
||||
func (m *MemoryOIDCProviderStore) GetProviderByIssuerAndAccount(ctx context.Context, _ string, issuer, accountID string) (*OIDCProviderRecord, error) {
|
||||
want := normalizeIssuer(issuer)
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
for _, rec := range m.providers {
|
||||
if normalizeIssuer(rec.URL) != want {
|
||||
continue
|
||||
}
|
||||
if rec.AccountID == "" || accountID == "" || rec.AccountID == accountID {
|
||||
return copyOIDCProviderRecord(rec), nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("no OIDC provider registered for issuer %s in account %s", issuer, accountID)
|
||||
}
|
||||
|
||||
// ListProviders returns every record sorted by ARN for stable output.
|
||||
func (m *MemoryOIDCProviderStore) ListProviders(ctx context.Context, _ string) ([]*OIDCProviderRecord, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
out := make([]*OIDCProviderRecord, 0, len(m.providers))
|
||||
for _, rec := range m.providers {
|
||||
out = append(out, copyOIDCProviderRecord(rec))
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ARN < out[j].ARN })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DeleteProvider removes the record. Idempotent — deleting a missing ARN is success.
|
||||
func (m *MemoryOIDCProviderStore) DeleteProvider(ctx context.Context, _ string, arn string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.providers, arn)
|
||||
return nil
|
||||
}
|
||||
|
||||
// FilerOIDCProviderStore persists records as JSON files in a filer directory,
|
||||
// mirroring FilerRoleStore.
|
||||
type FilerOIDCProviderStore struct {
|
||||
grpcDialOption grpc.DialOption
|
||||
basePath string
|
||||
filerAddressProvider func() string
|
||||
}
|
||||
|
||||
// NewFilerOIDCProviderStore returns a filer-backed store. Default path
|
||||
// `/etc/iam/oidc-providers` aligns with the existing roles directory.
|
||||
func NewFilerOIDCProviderStore(config map[string]interface{}, filerAddressProvider func() string) *FilerOIDCProviderStore {
|
||||
store := &FilerOIDCProviderStore{
|
||||
basePath: "/etc/iam/oidc-providers",
|
||||
filerAddressProvider: filerAddressProvider,
|
||||
}
|
||||
if config != nil {
|
||||
if bp, ok := config["basePath"].(string); ok && bp != "" {
|
||||
store.basePath = strings.TrimSuffix(bp, "/")
|
||||
}
|
||||
}
|
||||
glog.V(2).Infof("Initialized FilerOIDCProviderStore with basePath %s", store.basePath)
|
||||
return store
|
||||
}
|
||||
|
||||
func (f *FilerOIDCProviderStore) resolveFilerAddress(filerAddress string) string {
|
||||
if filerAddress != "" {
|
||||
return filerAddress
|
||||
}
|
||||
if f.filerAddressProvider != nil {
|
||||
return f.filerAddressProvider()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (f *FilerOIDCProviderStore) fileName(arn string) string {
|
||||
// Hash the ARN to a fixed-width filename so we can store any character set
|
||||
// (including the URL fragments AWS lets through) without filer-path issues.
|
||||
h := sha1.Sum([]byte(arn))
|
||||
return hex.EncodeToString(h[:]) + ".json"
|
||||
}
|
||||
|
||||
// StoreProvider persists `record` as JSON.
|
||||
func (f *FilerOIDCProviderStore) StoreProvider(ctx context.Context, filerAddress string, record *OIDCProviderRecord) error {
|
||||
filerAddress = f.resolveFilerAddress(filerAddress)
|
||||
if filerAddress == "" {
|
||||
return fmt.Errorf("filer address is required")
|
||||
}
|
||||
if record == nil || record.ARN == "" {
|
||||
return fmt.Errorf("record with ARN is required")
|
||||
}
|
||||
|
||||
data, err := json.MarshalIndent(record, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal OIDC provider: %v", err)
|
||||
}
|
||||
|
||||
return f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error {
|
||||
_, err := client.CreateEntry(ctx, &filer_pb.CreateEntryRequest{
|
||||
Directory: f.basePath,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: f.fileName(record.ARN),
|
||||
IsDirectory: false,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: time.Now().Unix(),
|
||||
Crtime: time.Now().Unix(),
|
||||
FileMode: uint32(0o600),
|
||||
},
|
||||
Content: data,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("store OIDC provider %s: %v", record.ARN, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// GetProviderByARN looks up the record file by its ARN-derived filename.
|
||||
func (f *FilerOIDCProviderStore) GetProviderByARN(ctx context.Context, filerAddress string, arn string) (*OIDCProviderRecord, error) {
|
||||
filerAddress = f.resolveFilerAddress(filerAddress)
|
||||
if filerAddress == "" {
|
||||
return nil, fmt.Errorf("filer address is required")
|
||||
}
|
||||
|
||||
var data []byte
|
||||
err := f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.LookupDirectoryEntry(ctx, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: f.basePath,
|
||||
Name: f.fileName(arn),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrOIDCProviderNotFound, err)
|
||||
}
|
||||
if resp.Entry == nil {
|
||||
return fmt.Errorf("OIDC provider not found: %s", arn)
|
||||
}
|
||||
data = resp.Entry.Content
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var rec OIDCProviderRecord
|
||||
if err := json.Unmarshal(data, &rec); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal OIDC provider: %v", err)
|
||||
}
|
||||
return &rec, nil
|
||||
}
|
||||
|
||||
// GetProviderByIssuer linearly scans the directory. Phase 2b adds an issuer
|
||||
// index when write throughput grows; for read-only this is good enough.
|
||||
func (f *FilerOIDCProviderStore) GetProviderByIssuer(ctx context.Context, filerAddress string, issuer string) (*OIDCProviderRecord, error) {
|
||||
records, err := f.ListProviders(ctx, filerAddress)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
want := normalizeIssuer(issuer)
|
||||
for _, rec := range records {
|
||||
if normalizeIssuer(rec.URL) == want {
|
||||
return rec, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("no OIDC provider registered for issuer: %s", issuer)
|
||||
}
|
||||
|
||||
// GetProviderByIssuerAndAccount filters by AccountID on top of the issuer scan.
|
||||
// See the MemoryOIDCProviderStore equivalent for semantics.
|
||||
func (f *FilerOIDCProviderStore) GetProviderByIssuerAndAccount(ctx context.Context, filerAddress string, issuer, accountID string) (*OIDCProviderRecord, error) {
|
||||
records, err := f.ListProviders(ctx, filerAddress)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
want := normalizeIssuer(issuer)
|
||||
for _, rec := range records {
|
||||
if normalizeIssuer(rec.URL) != want {
|
||||
continue
|
||||
}
|
||||
if rec.AccountID == "" || accountID == "" || rec.AccountID == accountID {
|
||||
return rec, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("no OIDC provider registered for issuer %s in account %s", issuer, accountID)
|
||||
}
|
||||
|
||||
// ListProviders enumerates every record in the directory.
|
||||
func (f *FilerOIDCProviderStore) ListProviders(ctx context.Context, filerAddress string) ([]*OIDCProviderRecord, error) {
|
||||
filerAddress = f.resolveFilerAddress(filerAddress)
|
||||
if filerAddress == "" {
|
||||
return nil, fmt.Errorf("filer address is required")
|
||||
}
|
||||
|
||||
var out []*OIDCProviderRecord
|
||||
err := f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error {
|
||||
// Stream-paginate via StartFromFileName so deployments with more
|
||||
// than 1000 providers don't get a silently truncated list.
|
||||
const pageSize = 1000
|
||||
startFrom := ""
|
||||
for {
|
||||
stream, err := client.ListEntries(ctx, &filer_pb.ListEntriesRequest{
|
||||
Directory: f.basePath,
|
||||
Limit: pageSize,
|
||||
StartFromFileName: startFrom,
|
||||
InclusiveStartFrom: false,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("list OIDC providers: %v", err)
|
||||
}
|
||||
lastName := ""
|
||||
pageCount := 0
|
||||
for {
|
||||
resp, recvErr := stream.Recv()
|
||||
if recvErr != nil {
|
||||
if errors.Is(recvErr, io.EOF) {
|
||||
break
|
||||
}
|
||||
return fmt.Errorf("recv OIDC provider entry: %w", recvErr)
|
||||
}
|
||||
if resp.Entry == nil || resp.Entry.IsDirectory {
|
||||
continue
|
||||
}
|
||||
lastName = resp.Entry.Name
|
||||
pageCount++
|
||||
if !strings.HasSuffix(resp.Entry.Name, ".json") {
|
||||
continue
|
||||
}
|
||||
var rec OIDCProviderRecord
|
||||
if err := json.Unmarshal(resp.Entry.Content, &rec); err != nil {
|
||||
glog.Warningf("skipping malformed OIDC provider record %s: %v", resp.Entry.Name, err)
|
||||
continue
|
||||
}
|
||||
out = append(out, &rec)
|
||||
}
|
||||
if pageCount < pageSize {
|
||||
break
|
||||
}
|
||||
startFrom = lastName
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ARN < out[j].ARN })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DeleteProvider removes the record. Missing ARN is treated as success.
|
||||
func (f *FilerOIDCProviderStore) DeleteProvider(ctx context.Context, filerAddress string, arn string) error {
|
||||
filerAddress = f.resolveFilerAddress(filerAddress)
|
||||
if filerAddress == "" {
|
||||
return fmt.Errorf("filer address is required")
|
||||
}
|
||||
return f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.DeleteEntry(ctx, &filer_pb.DeleteEntryRequest{
|
||||
Directory: f.basePath,
|
||||
Name: f.fileName(arn),
|
||||
IsDeleteData: true,
|
||||
})
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("delete OIDC provider %s: %v", arn, err)
|
||||
}
|
||||
if resp.Error != "" && !strings.Contains(resp.Error, "not found") {
|
||||
return fmt.Errorf("delete OIDC provider %s: %s", arn, resp.Error)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (f *FilerOIDCProviderStore) withFilerClient(filerAddress string, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), f.grpcDialOption, fn)
|
||||
}
|
||||
|
||||
// DeriveOIDCProviderARN turns an issuer URL into the canonical IAM ARN AWS uses.
|
||||
// Empty `accountID` produces a global-style ARN.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// https://accounts.google.com -> arn:aws:iam::<acct>:oidc-provider/accounts.google.com
|
||||
// https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED ->
|
||||
// arn:aws:iam::<acct>:oidc-provider/oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED
|
||||
func DeriveOIDCProviderARN(accountID, issuerURL string) (string, error) {
|
||||
if issuerURL == "" {
|
||||
return "", fmt.Errorf("issuer URL is required")
|
||||
}
|
||||
u, err := url.Parse(issuerURL)
|
||||
if err != nil || u.Host == "" {
|
||||
return "", fmt.Errorf("invalid issuer URL: %s", issuerURL)
|
||||
}
|
||||
host := strings.ToLower(u.Host)
|
||||
resource := host + strings.TrimSuffix(u.Path, "/")
|
||||
return fmt.Sprintf("arn:aws:iam::%s:oidc-provider/%s", accountID, resource), nil
|
||||
}
|
||||
|
||||
// normalizeIssuer compares-friendly form: lowercased host, no trailing slash.
|
||||
func normalizeIssuer(issuer string) string {
|
||||
u, err := url.Parse(issuer)
|
||||
if err != nil || u.Host == "" {
|
||||
return strings.TrimSuffix(strings.ToLower(issuer), "/")
|
||||
}
|
||||
u.Host = strings.ToLower(u.Host)
|
||||
u.Path = strings.TrimSuffix(u.Path, "/")
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func copyOIDCProviderRecord(rec *OIDCProviderRecord) *OIDCProviderRecord {
|
||||
if rec == nil {
|
||||
return nil
|
||||
}
|
||||
cp := *rec
|
||||
if rec.ClientIDs != nil {
|
||||
cp.ClientIDs = append([]string(nil), rec.ClientIDs...)
|
||||
}
|
||||
if rec.Thumbprints != nil {
|
||||
cp.Thumbprints = append([]string(nil), rec.Thumbprints...)
|
||||
}
|
||||
if rec.AllowedPrincipalTagKeys != nil {
|
||||
cp.AllowedPrincipalTagKeys = append([]string(nil), rec.AllowedPrincipalTagKeys...)
|
||||
}
|
||||
if rec.Tags != nil {
|
||||
cp.Tags = make(map[string]string, len(rec.Tags))
|
||||
for k, v := range rec.Tags {
|
||||
cp.Tags[k] = v
|
||||
}
|
||||
}
|
||||
return &cp
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newRecord(arn, url string) *OIDCProviderRecord {
|
||||
now := time.Now()
|
||||
return &OIDCProviderRecord{
|
||||
ARN: arn,
|
||||
URL: url,
|
||||
ClientIDs: []string{"sts.amazonaws.com"},
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryStoreCRUD(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewMemoryOIDCProviderStore()
|
||||
|
||||
rec := newRecord(
|
||||
"arn:aws:iam::123:oidc-provider/token.actions.githubusercontent.com",
|
||||
"https://token.actions.githubusercontent.com",
|
||||
)
|
||||
|
||||
// Store + Get round-trip preserves the record.
|
||||
if err := store.StoreProvider(ctx, "", rec); err != nil {
|
||||
t.Fatalf("StoreProvider: %v", err)
|
||||
}
|
||||
got, err := store.GetProviderByARN(ctx, "", rec.ARN)
|
||||
if err != nil {
|
||||
t.Fatalf("GetProviderByARN: %v", err)
|
||||
}
|
||||
if got.URL != rec.URL {
|
||||
t.Fatalf("URL mismatch: got=%s want=%s", got.URL, rec.URL)
|
||||
}
|
||||
|
||||
// Mutate the returned copy and verify the store wasn't affected.
|
||||
got.ClientIDs[0] = "tampered"
|
||||
again, _ := store.GetProviderByARN(ctx, "", rec.ARN)
|
||||
if again.ClientIDs[0] == "tampered" {
|
||||
t.Fatal("store handed out a shared slice; mutations leaked back")
|
||||
}
|
||||
|
||||
// List returns the entry.
|
||||
all, err := store.ListProviders(ctx, "")
|
||||
if err != nil {
|
||||
t.Fatalf("ListProviders: %v", err)
|
||||
}
|
||||
if len(all) != 1 || all[0].ARN != rec.ARN {
|
||||
t.Fatalf("ListProviders unexpected result: %+v", all)
|
||||
}
|
||||
|
||||
// Delete -> Get returns not found.
|
||||
if err := store.DeleteProvider(ctx, "", rec.ARN); err != nil {
|
||||
t.Fatalf("DeleteProvider: %v", err)
|
||||
}
|
||||
if _, err := store.GetProviderByARN(ctx, "", rec.ARN); err == nil {
|
||||
t.Fatal("expected not-found after delete")
|
||||
}
|
||||
// Delete is idempotent.
|
||||
if err := store.DeleteProvider(ctx, "", rec.ARN); err != nil {
|
||||
t.Fatalf("idempotent delete should succeed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryStoreGetByIssuerNormalizesHost(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewMemoryOIDCProviderStore()
|
||||
|
||||
rec := newRecord(
|
||||
"arn:aws:iam::123:oidc-provider/token.actions.githubusercontent.com",
|
||||
"https://Token.Actions.GithubUserContent.com/", // mixed case + trailing slash
|
||||
)
|
||||
if err := store.StoreProvider(ctx, "", rec); err != nil {
|
||||
t.Fatalf("StoreProvider: %v", err)
|
||||
}
|
||||
|
||||
cases := []string{
|
||||
"https://token.actions.githubusercontent.com",
|
||||
"https://token.actions.githubusercontent.com/",
|
||||
"https://TOKEN.actions.GITHUBUSERCONTENT.com",
|
||||
}
|
||||
for _, want := range cases {
|
||||
got, err := store.GetProviderByIssuer(ctx, "", want)
|
||||
if err != nil {
|
||||
t.Errorf("issuer %q: GetProviderByIssuer: %v", want, err)
|
||||
continue
|
||||
}
|
||||
if got.ARN != rec.ARN {
|
||||
t.Errorf("issuer %q: ARN mismatch: got=%s", want, got.ARN)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryStoreGetByIssuerMissing(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewMemoryOIDCProviderStore()
|
||||
_, err := store.GetProviderByIssuer(ctx, "", "https://other.example/")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for unregistered issuer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeriveOIDCProviderARN(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
accountID string
|
||||
issuer string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "google",
|
||||
accountID: "111122223333",
|
||||
issuer: "https://accounts.google.com",
|
||||
want: "arn:aws:iam::111122223333:oidc-provider/accounts.google.com",
|
||||
},
|
||||
{
|
||||
name: "EKS with path",
|
||||
accountID: "999999999999",
|
||||
issuer: "https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED",
|
||||
want: "arn:aws:iam::999999999999:oidc-provider/oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED",
|
||||
},
|
||||
{
|
||||
name: "uppercase host normalized",
|
||||
accountID: "111122223333",
|
||||
issuer: "https://Accounts.Google.com",
|
||||
want: "arn:aws:iam::111122223333:oidc-provider/accounts.google.com",
|
||||
},
|
||||
{
|
||||
name: "trailing slash trimmed",
|
||||
accountID: "111122223333",
|
||||
issuer: "https://accounts.google.com/",
|
||||
want: "arn:aws:iam::111122223333:oidc-provider/accounts.google.com",
|
||||
},
|
||||
{
|
||||
name: "empty account allowed",
|
||||
accountID: "",
|
||||
issuer: "https://accounts.google.com",
|
||||
want: "arn:aws:iam:::oidc-provider/accounts.google.com",
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := DeriveOIDCProviderARN(tc.accountID, tc.issuer)
|
||||
if err != nil {
|
||||
t.Fatalf("err: %v", err)
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Fatalf("got=%s want=%s", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeriveOIDCProviderARNRejectsBadInput(t *testing.T) {
|
||||
cases := []string{"", "not a url", "http://"}
|
||||
for _, in := range cases {
|
||||
if _, err := DeriveOIDCProviderARN("123", in); err == nil {
|
||||
t.Errorf("expected error for input %q", in)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreRejectsEmptyARN(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewMemoryOIDCProviderStore()
|
||||
rec := newRecord("", "https://issuer/")
|
||||
if err := store.StoreProvider(ctx, "", rec); err == nil {
|
||||
t.Fatal("expected error storing record with empty ARN")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreRejectsNil(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewMemoryOIDCProviderStore()
|
||||
if err := store.StoreProvider(ctx, "", nil); err == nil {
|
||||
t.Fatal("expected error storing nil record")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeIssuerRejectsEmpty(t *testing.T) {
|
||||
if got := normalizeIssuer(""); got != "" {
|
||||
t.Fatalf("empty issuer should normalize to empty, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeIssuerHandlesNonURL(t *testing.T) {
|
||||
// Defense in depth: even when issuer is junk, normalize doesn't panic and
|
||||
// at least lowercases the input.
|
||||
got := normalizeIssuer("Some Random String/")
|
||||
if !strings.Contains(got, "some random") {
|
||||
t.Fatalf("normalize should lowercase non-URL input, got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package integration
|
||||
|
||||
import "testing"
|
||||
|
||||
func intPtr(v int64) *int64 { return &v }
|
||||
|
||||
func TestCapDurationByRole(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
requested *int64
|
||||
roleMax int64
|
||||
want *int64
|
||||
}{
|
||||
{"no cap, no request", nil, 0, nil},
|
||||
{"no cap, with request", intPtr(7200), 0, intPtr(7200)},
|
||||
{"cap only, no request -> nil so STS default applies", nil, 3600, nil},
|
||||
{"request below cap -> request", intPtr(1800), 3600, intPtr(1800)},
|
||||
{"request equal cap -> request", intPtr(3600), 3600, intPtr(3600)},
|
||||
{"request above cap -> cap", intPtr(43200), 3600, intPtr(3600)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := capDurationByRole(tc.requested, tc.roleMax)
|
||||
switch {
|
||||
case got == nil && tc.want == nil:
|
||||
return
|
||||
case got == nil || tc.want == nil:
|
||||
t.Fatalf("nilness mismatch: got=%v want=%v", got, tc.want)
|
||||
case *got != *tc.want:
|
||||
t.Fatalf("got=%d want=%d", *got, *tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// RevocationEntry is one row in the revocation list. ExpiresAt is set to the
|
||||
// session's natural expiration so the store can garbage-collect entries that
|
||||
// can no longer be reused.
|
||||
type RevocationEntry struct {
|
||||
JTI string `json:"jti"`
|
||||
RevokedAt time.Time `json:"revokedAt"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
// SessionRevocationStore is the per-deployment blocklist of revoked sessions.
|
||||
// Implementations must be safe for concurrent use; the IsRevoked path is hot
|
||||
// (checked on every signed request) and must not block on slow IO.
|
||||
type SessionRevocationStore interface {
|
||||
Revoke(ctx context.Context, filerAddress string, entry *RevocationEntry) error
|
||||
IsRevoked(ctx context.Context, filerAddress string, jti string) (bool, error)
|
||||
Purge(ctx context.Context, filerAddress string, before time.Time) (int, error)
|
||||
}
|
||||
|
||||
// MemorySessionRevocationStore keeps the blocklist in process memory. Suitable
|
||||
// for single-node deployments and tests; for HA, swap in the filer-backed
|
||||
// implementation so revocations propagate across `weed` instances.
|
||||
type MemorySessionRevocationStore struct {
|
||||
mu sync.RWMutex
|
||||
entries map[string]*RevocationEntry
|
||||
}
|
||||
|
||||
// NewMemorySessionRevocationStore returns an empty in-memory blocklist.
|
||||
func NewMemorySessionRevocationStore() *MemorySessionRevocationStore {
|
||||
return &MemorySessionRevocationStore{entries: make(map[string]*RevocationEntry)}
|
||||
}
|
||||
|
||||
func (m *MemorySessionRevocationStore) Revoke(ctx context.Context, _ string, entry *RevocationEntry) error {
|
||||
if entry == nil || entry.JTI == "" {
|
||||
return fmt.Errorf("entry with JTI is required")
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
cp := *entry
|
||||
if cp.RevokedAt.IsZero() {
|
||||
cp.RevokedAt = time.Now().UTC()
|
||||
}
|
||||
m.entries[entry.JTI] = &cp
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MemorySessionRevocationStore) IsRevoked(ctx context.Context, _ string, jti string) (bool, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
_, ok := m.entries[jti]
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func (m *MemorySessionRevocationStore) Purge(ctx context.Context, _ string, before time.Time) (int, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
count := 0
|
||||
for k, v := range m.entries {
|
||||
if !v.ExpiresAt.IsZero() && v.ExpiresAt.Before(before) {
|
||||
delete(m.entries, k)
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// FilerSessionRevocationStore persists entries under a filer directory.
|
||||
// Files are named after the JTI so IsRevoked is a single LookupDirectoryEntry
|
||||
// call — O(1) on a name-indexed filer. Purge enumerates the directory; that
|
||||
// cost is operator-controlled (cron-driven) so the hot path stays cheap.
|
||||
type FilerSessionRevocationStore struct {
|
||||
grpcDialOption grpc.DialOption
|
||||
basePath string
|
||||
filerAddressProvider func() string
|
||||
}
|
||||
|
||||
// NewFilerSessionRevocationStore returns a filer-backed blocklist store.
|
||||
// Default basePath `/etc/iam/revoked-sessions` aligns with the other IAM
|
||||
// directories and is safe to back up alongside roles + providers.
|
||||
func NewFilerSessionRevocationStore(config map[string]interface{}, filerAddressProvider func() string) *FilerSessionRevocationStore {
|
||||
store := &FilerSessionRevocationStore{
|
||||
basePath: "/etc/iam/revoked-sessions",
|
||||
filerAddressProvider: filerAddressProvider,
|
||||
}
|
||||
if config != nil {
|
||||
if bp, ok := config["basePath"].(string); ok && bp != "" {
|
||||
store.basePath = strings.TrimSuffix(bp, "/")
|
||||
}
|
||||
}
|
||||
glog.V(2).Infof("Initialized FilerSessionRevocationStore with basePath %s", store.basePath)
|
||||
return store
|
||||
}
|
||||
|
||||
func (f *FilerSessionRevocationStore) resolveFilerAddress(filerAddress string) string {
|
||||
if filerAddress != "" {
|
||||
return filerAddress
|
||||
}
|
||||
if f.filerAddressProvider != nil {
|
||||
return f.filerAddressProvider()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// fileName hashes the JTI before using it as a filename. RevokeSession is
|
||||
// an exported API that accepts an arbitrary string; even though every
|
||||
// SeaweedFS-issued session id is a safe random token, an external caller
|
||||
// could pass "../../etc/passwd" or similar. Hashing produces a fixed-width
|
||||
// hex name that's both filesystem-safe and stable, so the lookup-on-revoke
|
||||
// path still finds the right entry.
|
||||
func (f *FilerSessionRevocationStore) fileName(jti string) string {
|
||||
sum := sha1.Sum([]byte(jti))
|
||||
return hex.EncodeToString(sum[:]) + ".json"
|
||||
}
|
||||
|
||||
func (f *FilerSessionRevocationStore) Revoke(ctx context.Context, filerAddress string, entry *RevocationEntry) error {
|
||||
filerAddress = f.resolveFilerAddress(filerAddress)
|
||||
if filerAddress == "" {
|
||||
return fmt.Errorf("filer address is required")
|
||||
}
|
||||
if entry == nil || entry.JTI == "" {
|
||||
return fmt.Errorf("entry with JTI is required")
|
||||
}
|
||||
if entry.RevokedAt.IsZero() {
|
||||
entry.RevokedAt = time.Now().UTC()
|
||||
}
|
||||
data, err := json.MarshalIndent(entry, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal revocation entry: %v", err)
|
||||
}
|
||||
return f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error {
|
||||
_, err := client.CreateEntry(ctx, &filer_pb.CreateEntryRequest{
|
||||
Directory: f.basePath,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: f.fileName(entry.JTI),
|
||||
IsDirectory: false,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: time.Now().Unix(),
|
||||
Crtime: time.Now().Unix(),
|
||||
FileMode: uint32(0o600),
|
||||
},
|
||||
Content: data,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("revoke %s: %v", entry.JTI, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (f *FilerSessionRevocationStore) IsRevoked(ctx context.Context, filerAddress string, jti string) (bool, error) {
|
||||
filerAddress = f.resolveFilerAddress(filerAddress)
|
||||
if filerAddress == "" {
|
||||
return false, fmt.Errorf("filer address is required")
|
||||
}
|
||||
revoked := false
|
||||
err := f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.LookupDirectoryEntry(ctx, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: f.basePath,
|
||||
Name: f.fileName(jti),
|
||||
})
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "not found") || strings.Contains(err.Error(), "no such") {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
revoked = resp.Entry != nil
|
||||
return nil
|
||||
})
|
||||
return revoked, err
|
||||
}
|
||||
|
||||
func (f *FilerSessionRevocationStore) Purge(ctx context.Context, filerAddress string, before time.Time) (int, error) {
|
||||
filerAddress = f.resolveFilerAddress(filerAddress)
|
||||
if filerAddress == "" {
|
||||
return 0, fmt.Errorf("filer address is required")
|
||||
}
|
||||
count := 0
|
||||
err := f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error {
|
||||
// Stream-paginate the directory: ListEntriesRequest has no built-in
|
||||
// "page until done" semantics, so we use StartFromFileName to walk
|
||||
// the directory in chunks and avoid the previous hardcoded 10k cap.
|
||||
const pageSize = 1000
|
||||
startFrom := ""
|
||||
for {
|
||||
stream, err := client.ListEntries(ctx, &filer_pb.ListEntriesRequest{
|
||||
Directory: f.basePath,
|
||||
Limit: pageSize,
|
||||
StartFromFileName: startFrom,
|
||||
InclusiveStartFrom: false,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("list revocation entries: %w", err)
|
||||
}
|
||||
lastName := ""
|
||||
pageCount := 0
|
||||
for {
|
||||
resp, recvErr := stream.Recv()
|
||||
if recvErr != nil {
|
||||
if errors.Is(recvErr, io.EOF) {
|
||||
break
|
||||
}
|
||||
return fmt.Errorf("recv revocation entry: %w", recvErr)
|
||||
}
|
||||
if resp.Entry == nil || resp.Entry.IsDirectory {
|
||||
continue
|
||||
}
|
||||
lastName = resp.Entry.Name
|
||||
pageCount++
|
||||
var entry RevocationEntry
|
||||
if err := json.Unmarshal(resp.Entry.Content, &entry); err != nil {
|
||||
continue
|
||||
}
|
||||
if entry.ExpiresAt.IsZero() || entry.ExpiresAt.After(before) {
|
||||
continue
|
||||
}
|
||||
if _, err := client.DeleteEntry(ctx, &filer_pb.DeleteEntryRequest{
|
||||
Directory: f.basePath,
|
||||
Name: resp.Entry.Name,
|
||||
IsDeleteData: true,
|
||||
}); err == nil {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if pageCount < pageSize {
|
||||
return nil
|
||||
}
|
||||
startFrom = lastName
|
||||
}
|
||||
})
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (f *FilerSessionRevocationStore) withFilerClient(filerAddress string, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), f.grpcDialOption, fn)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMemoryRevocationStoreCRUD(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewMemorySessionRevocationStore()
|
||||
|
||||
if revoked, _ := store.IsRevoked(ctx, "", "abc"); revoked {
|
||||
t.Fatal("empty store should report not revoked")
|
||||
}
|
||||
|
||||
if err := store.Revoke(ctx, "", &RevocationEntry{JTI: "abc", ExpiresAt: time.Now().Add(time.Hour)}); err != nil {
|
||||
t.Fatalf("revoke: %v", err)
|
||||
}
|
||||
if revoked, _ := store.IsRevoked(ctx, "", "abc"); !revoked {
|
||||
t.Fatal("expected revoked")
|
||||
}
|
||||
// Different JTIs are independent.
|
||||
if revoked, _ := store.IsRevoked(ctx, "", "xyz"); revoked {
|
||||
t.Fatal("xyz should not be revoked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRevocationStoreRejectsBadInput(t *testing.T) {
|
||||
store := NewMemorySessionRevocationStore()
|
||||
if err := store.Revoke(context.Background(), "", nil); err == nil {
|
||||
t.Fatal("expected error for nil entry")
|
||||
}
|
||||
if err := store.Revoke(context.Background(), "", &RevocationEntry{}); err == nil {
|
||||
t.Fatal("expected error for empty JTI")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRevocationStorePurge(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewMemorySessionRevocationStore()
|
||||
now := time.Now()
|
||||
|
||||
must := func(jti string, expiresAt time.Time) {
|
||||
if err := store.Revoke(ctx, "", &RevocationEntry{JTI: jti, ExpiresAt: expiresAt}); err != nil {
|
||||
t.Fatalf("revoke %s: %v", jti, err)
|
||||
}
|
||||
}
|
||||
must("expired-1", now.Add(-2*time.Hour))
|
||||
must("expired-2", now.Add(-time.Minute))
|
||||
must("future-1", now.Add(time.Hour))
|
||||
|
||||
count, err := store.Purge(ctx, "", now)
|
||||
if err != nil {
|
||||
t.Fatalf("purge: %v", err)
|
||||
}
|
||||
if count != 2 {
|
||||
t.Fatalf("expected 2 purged, got %d", count)
|
||||
}
|
||||
if revoked, _ := store.IsRevoked(ctx, "", "expired-1"); revoked {
|
||||
t.Fatal("expired-1 should be gone")
|
||||
}
|
||||
if revoked, _ := store.IsRevoked(ctx, "", "future-1"); !revoked {
|
||||
t.Fatal("future-1 should still be revoked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMManagerRevocationDefaultIsNoop(t *testing.T) {
|
||||
mgr := NewIAMManager()
|
||||
// Without SetSessionRevocationStore, revocation is a no-op.
|
||||
if got, err := mgr.IsSessionRevoked(context.Background(), "anything"); err != nil || got {
|
||||
t.Fatalf("expected (false, nil); got (%v, %v)", got, err)
|
||||
}
|
||||
if err := mgr.RevokeSession(context.Background(), "abc", time.Now().Add(time.Hour), "test"); err == nil {
|
||||
t.Fatal("expected error when no store configured")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMManagerRevocationFlow(t *testing.T) {
|
||||
mgr := NewIAMManager()
|
||||
mgr.SetSessionRevocationStore(NewMemorySessionRevocationStore())
|
||||
|
||||
jti := "session-1"
|
||||
if err := mgr.RevokeSession(context.Background(), jti, time.Now().Add(time.Hour), "logout"); err != nil {
|
||||
t.Fatalf("RevokeSession: %v", err)
|
||||
}
|
||||
revoked, err := mgr.IsSessionRevoked(context.Background(), jti)
|
||||
if err != nil {
|
||||
t.Fatalf("IsSessionRevoked: %v", err)
|
||||
}
|
||||
if !revoked {
|
||||
t.Fatal("expected revoked")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeIDP wraps an httptest.Server and counts how many times each well-known
|
||||
// endpoint is hit. Tests use it to assert discovery vs. fallback behaviour.
|
||||
type fakeIDP struct {
|
||||
server *httptest.Server
|
||||
discoveryHits atomic.Int32
|
||||
jwksHits atomic.Int32
|
||||
customJWKSHits atomic.Int32
|
||||
disableDiscovery bool
|
||||
discoveryStatusCode int
|
||||
discoveryIssuer string
|
||||
omitDiscoveryIssuer bool // when true, the discovery doc omits the "issuer" field entirely
|
||||
customJWKSPathSuffix string // optional suffix that fakeIDP serves at /custom/<suffix>
|
||||
jwks JWKS
|
||||
}
|
||||
|
||||
func newFakeIDP(t *testing.T) *fakeIDP {
|
||||
t.Helper()
|
||||
idp := &fakeIDP{
|
||||
discoveryStatusCode: http.StatusOK,
|
||||
jwks: JWKS{Keys: []JWK{{Kty: "RSA", Kid: "k1", Use: "sig", Alg: "RS256", N: "AQAB", E: "AQAB"}}},
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
|
||||
idp.discoveryHits.Add(1)
|
||||
if idp.disableDiscovery {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(idp.discoveryStatusCode)
|
||||
issuer := idp.discoveryIssuer
|
||||
if issuer == "" {
|
||||
issuer = idp.server.URL
|
||||
}
|
||||
jwksURI := idp.server.URL + "/discovered/jwks"
|
||||
if idp.customJWKSPathSuffix != "" {
|
||||
jwksURI = idp.server.URL + "/custom/" + idp.customJWKSPathSuffix
|
||||
}
|
||||
body := map[string]string{"jwks_uri": jwksURI}
|
||||
if !idp.omitDiscoveryIssuer {
|
||||
body["issuer"] = issuer
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
})
|
||||
mux.HandleFunc("/discovered/jwks", func(w http.ResponseWriter, r *http.Request) {
|
||||
idp.jwksHits.Add(1)
|
||||
_ = json.NewEncoder(w).Encode(idp.jwks)
|
||||
})
|
||||
mux.HandleFunc("/.well-known/jwks.json", func(w http.ResponseWriter, r *http.Request) {
|
||||
idp.jwksHits.Add(1)
|
||||
_ = json.NewEncoder(w).Encode(idp.jwks)
|
||||
})
|
||||
mux.HandleFunc("/custom/", func(w http.ResponseWriter, r *http.Request) {
|
||||
idp.customJWKSHits.Add(1)
|
||||
_ = json.NewEncoder(w).Encode(idp.jwks)
|
||||
})
|
||||
idp.server = httptest.NewServer(mux)
|
||||
t.Cleanup(idp.server.Close)
|
||||
return idp
|
||||
}
|
||||
|
||||
func newProviderForIDP(t *testing.T, idp *fakeIDP, jwksURIOverride string) *OIDCProvider {
|
||||
t.Helper()
|
||||
p := NewOIDCProvider("test")
|
||||
cfg := &OIDCConfig{
|
||||
Issuer: idp.server.URL,
|
||||
ClientID: "test-client",
|
||||
JWKSUri: jwksURIOverride,
|
||||
}
|
||||
if err := p.Initialize(cfg); err != nil {
|
||||
t.Fatalf("Initialize: %v", err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func TestDiscoveryHappyPath(t *testing.T) {
|
||||
idp := newFakeIDP(t)
|
||||
p := newProviderForIDP(t, idp, "")
|
||||
|
||||
if err := p.fetchJWKS(context.Background()); err != nil {
|
||||
t.Fatalf("fetchJWKS: %v", err)
|
||||
}
|
||||
if got := idp.discoveryHits.Load(); got != 1 {
|
||||
t.Fatalf("expected 1 discovery hit, got %d", got)
|
||||
}
|
||||
if got := idp.jwksHits.Load(); got != 1 {
|
||||
t.Fatalf("expected 1 JWKS hit at discovered uri, got %d", got)
|
||||
}
|
||||
|
||||
// A second fetch reuses the cached jwks_uri without re-discovering.
|
||||
if err := p.fetchJWKS(context.Background()); err != nil {
|
||||
t.Fatalf("fetchJWKS second: %v", err)
|
||||
}
|
||||
if got := idp.discoveryHits.Load(); got != 1 {
|
||||
t.Fatalf("discovery should be cached, got %d hits", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoveryFallback404(t *testing.T) {
|
||||
idp := newFakeIDP(t)
|
||||
idp.disableDiscovery = true
|
||||
p := newProviderForIDP(t, idp, "")
|
||||
|
||||
if err := p.fetchJWKS(context.Background()); err != nil {
|
||||
t.Fatalf("fetchJWKS: %v", err)
|
||||
}
|
||||
if got := idp.discoveryHits.Load(); got != 1 {
|
||||
t.Fatalf("expected 1 discovery probe, got %d", got)
|
||||
}
|
||||
if got := idp.jwksHits.Load(); got != 1 {
|
||||
t.Fatalf("expected 1 JWKS hit at fallback uri, got %d", got)
|
||||
}
|
||||
|
||||
// Subsequent fetches retry discovery — discoveryFailed resets at the top
|
||||
// of fetchJWKSLocked when no URI was cached, so a transient 5xx at
|
||||
// startup doesn't lock the provider into the fallback path forever.
|
||||
// Retry rate is bounded by the JWKS TTL (one retry per refresh cycle).
|
||||
if err := p.fetchJWKS(context.Background()); err != nil {
|
||||
t.Fatalf("fetchJWKS second: %v", err)
|
||||
}
|
||||
if got := idp.discoveryHits.Load(); got != 2 {
|
||||
t.Fatalf("discovery probe should retry while no URI is cached, got %d hits", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoveryDisabledByExplicitJWKSUri(t *testing.T) {
|
||||
idp := newFakeIDP(t)
|
||||
override := idp.server.URL + "/custom/explicit"
|
||||
idp.customJWKSPathSuffix = "explicit"
|
||||
p := newProviderForIDP(t, idp, override)
|
||||
|
||||
if err := p.fetchJWKS(context.Background()); err != nil {
|
||||
t.Fatalf("fetchJWKS: %v", err)
|
||||
}
|
||||
if got := idp.discoveryHits.Load(); got != 0 {
|
||||
t.Fatalf("explicit JWKSUri should bypass discovery, got %d hits", got)
|
||||
}
|
||||
if got := idp.customJWKSHits.Load(); got != 1 {
|
||||
t.Fatalf("expected 1 custom JWKS hit, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoveryRejectsIssuerMismatch(t *testing.T) {
|
||||
idp := newFakeIDP(t)
|
||||
idp.discoveryIssuer = "https://attacker.example/"
|
||||
p := newProviderForIDP(t, idp, "")
|
||||
|
||||
if err := p.fetchJWKS(context.Background()); err != nil {
|
||||
t.Fatalf("fetchJWKS should fall back to /.well-known/jwks.json, got error: %v", err)
|
||||
}
|
||||
// Discovery probe was tried once, rejected, then fell through to fallback path.
|
||||
if got := idp.discoveryHits.Load(); got != 1 {
|
||||
t.Fatalf("expected 1 discovery probe, got %d", got)
|
||||
}
|
||||
if got := idp.jwksHits.Load(); got != 1 {
|
||||
t.Fatalf("expected 1 fallback JWKS hit, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDiscoveryRejectsMissingIssuer: a discovery document that omits the
|
||||
// issuer field entirely must be treated the same as one that supplies a
|
||||
// mismatched issuer. Otherwise an attacker who can intercept the discovery
|
||||
// response can strip the issuer field and the comparison silently passes,
|
||||
// letting the document point fetchJWKS at any URL it pleases.
|
||||
func TestDiscoveryRejectsMissingIssuer(t *testing.T) {
|
||||
idp := newFakeIDP(t)
|
||||
idp.omitDiscoveryIssuer = true
|
||||
p := newProviderForIDP(t, idp, "")
|
||||
|
||||
if err := p.fetchJWKS(context.Background()); err != nil {
|
||||
t.Fatalf("fetchJWKS should fall back to /.well-known/jwks.json on issuer-missing discovery: %v", err)
|
||||
}
|
||||
if got := idp.discoveryHits.Load(); got != 1 {
|
||||
t.Fatalf("expected 1 discovery probe, got %d", got)
|
||||
}
|
||||
// The discovery document was rejected; the JWKS that ultimately served
|
||||
// us must be the fallback one, not the discovered URI. The fakeIDP
|
||||
// counts both hits under jwksHits since they share a counter; what
|
||||
// matters is that customJWKSHits stayed zero.
|
||||
if got := idp.customJWKSHits.Load(); got != 0 {
|
||||
t.Fatalf("custom JWKS endpoint must not have been used, got %d hits", got)
|
||||
}
|
||||
if got := idp.jwksHits.Load(); got != 1 {
|
||||
t.Fatalf("expected 1 fallback JWKS hit, got %d", got)
|
||||
}
|
||||
}
|
||||
+448
-39
@@ -5,9 +5,11 @@ import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rsa"
|
||||
"crypto/sha1"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -16,6 +18,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
@@ -25,13 +28,21 @@ import (
|
||||
|
||||
// OIDCProvider implements OpenID Connect authentication
|
||||
type OIDCProvider struct {
|
||||
name string
|
||||
config *OIDCConfig
|
||||
initialized bool
|
||||
jwksCache *JWKS
|
||||
httpClient *http.Client
|
||||
jwksFetchedAt time.Time
|
||||
jwksTTL time.Duration
|
||||
name string
|
||||
config *OIDCConfig
|
||||
initialized bool
|
||||
httpClient *http.Client
|
||||
jwksTTL time.Duration
|
||||
|
||||
// mu guards the lazily-mutated cache fields below: jwksCache, jwksFetchedAt,
|
||||
// resolvedJWKSUri, and discoveryFailed are all populated on the first
|
||||
// validate-token call and refreshed when the cache expires. Multiple S3
|
||||
// requests can land here in parallel, so they need synchronization.
|
||||
mu sync.RWMutex
|
||||
jwksCache *JWKS
|
||||
jwksFetchedAt time.Time
|
||||
resolvedJWKSUri string
|
||||
discoveryFailed bool
|
||||
}
|
||||
|
||||
// OIDCConfig holds OIDC provider configuration
|
||||
@@ -39,8 +50,15 @@ type OIDCConfig struct {
|
||||
// Issuer is the OIDC issuer URL
|
||||
Issuer string `json:"issuer"`
|
||||
|
||||
// ClientID is the OAuth2 client ID
|
||||
ClientID string `json:"clientId"`
|
||||
// ClientID is the OAuth2 client ID. Either ClientID or ClientIDs is
|
||||
// required; when both are present, ClientID is appended to the audience
|
||||
// allowlist.
|
||||
ClientID string `json:"clientId,omitempty"`
|
||||
|
||||
// ClientIDs is the AWS-compatible audience allowlist. Tokens are accepted
|
||||
// when any of `aud` or `azp` matches any entry. Mutually compatible with
|
||||
// ClientID for backward compatibility.
|
||||
ClientIDs []string `json:"clientIds,omitempty"`
|
||||
|
||||
// ClientSecret is the OAuth2 client secret (optional for public clients)
|
||||
ClientSecret string `json:"clientSecret,omitempty"`
|
||||
@@ -63,6 +81,25 @@ type OIDCConfig struct {
|
||||
// JWKSCacheTTLSeconds sets how long to cache JWKS before refresh (default 3600 seconds)
|
||||
JWKSCacheTTLSeconds int `json:"jwksCacheTTLSeconds,omitempty"`
|
||||
|
||||
// Thumbprints, when non-empty, pins the issuer's TLS certificate against
|
||||
// this allowlist of SHA-1 hex digests. Matches the AWS IAM
|
||||
// CreateOpenIDConnectProvider semantics. Empty means "trust the system
|
||||
// root store" (or whatever TLSCACert configures).
|
||||
Thumbprints []string `json:"thumbprints,omitempty"`
|
||||
|
||||
// AllowedPrincipalTagKeys filters the keys read from the AWS principal
|
||||
// session tags claim. Empty means "no tags surfaced". Provide an explicit
|
||||
// allowlist (e.g. ["team", "env"]) to opt specific keys in.
|
||||
AllowedPrincipalTagKeys []string `json:"allowedPrincipalTagKeys,omitempty"`
|
||||
|
||||
// PolicyClaim names a JWT claim whose value carries the effective policy
|
||||
// list for the session. When non-empty and the assume request opts into
|
||||
// claim-based policy mode via the ClaimBasedPolicyRoleArn sentinel, the
|
||||
// policies are pulled from this claim rather than from a server-side
|
||||
// role mapping. Accepted shapes: string (single policy), comma-separated
|
||||
// string, or string array.
|
||||
PolicyClaim string `json:"policyClaim,omitempty"`
|
||||
|
||||
// TLSCACert is the path to the CA certificate file for custom/self-signed certificates
|
||||
TLSCACert string `json:"tlsCaCert,omitempty"`
|
||||
|
||||
@@ -71,6 +108,193 @@ type OIDCConfig struct {
|
||||
TLSInsecureSkipVerify bool `json:"tlsInsecureSkipVerify,omitempty"`
|
||||
}
|
||||
|
||||
// PrincipalTagsClaim is the AWS-defined namespace claim that carries
|
||||
// principal session tags. Tokens that include this claim must encode it as
|
||||
// an object whose top-level keys are tag names. AWS uses the same string;
|
||||
// see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html.
|
||||
const PrincipalTagsClaim = "https://aws.amazon.com/tags/principal_tags"
|
||||
|
||||
// extractClaimPolicies reads policy names from the configured JWT claim.
|
||||
// Accepts three shapes: a single string ("readonly"), a comma-separated
|
||||
// string ("readonly,billing"), or a string array. Returns nil when the
|
||||
// provider isn't in claim-based mode or the claim is absent/empty.
|
||||
func extractClaimPolicies(claims map[string]interface{}, claimName string) []string {
|
||||
if claimName == "" {
|
||||
return nil
|
||||
}
|
||||
raw, ok := claims[claimName]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
switch v := raw.(type) {
|
||||
case string:
|
||||
return splitPolicyClaimString(v)
|
||||
case []interface{}:
|
||||
out := make([]string, 0, len(v))
|
||||
for _, e := range v {
|
||||
s, ok := e.(string)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
continue
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func splitPolicyClaimString(s string) []string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
parts := strings.Split(s, ",")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// filterPrincipalTags drops keys that are not on `allowed`. An empty
|
||||
// allowlist means "deny all" — security-conservative default that forces
|
||||
// operators to explicitly opt tags in. Returns nil when the result is empty.
|
||||
//
|
||||
// Comparison is case-insensitive on the key, matching AWS IAM's session-tag
|
||||
// rules (the AWS docs explicitly state tag keys are case-insensitive even
|
||||
// though the original casing is preserved on the value side). Without this
|
||||
// an IDP whose claim casing drifts from the operator's allowlist string
|
||||
// would fail in surprising ways.
|
||||
func filterPrincipalTags(tags map[string]string, allowed []string) map[string]string {
|
||||
if len(tags) == 0 {
|
||||
return nil
|
||||
}
|
||||
if len(allowed) == 0 {
|
||||
return nil
|
||||
}
|
||||
allowSet := make(map[string]struct{}, len(allowed))
|
||||
for _, k := range allowed {
|
||||
allowSet[strings.ToLower(k)] = struct{}{}
|
||||
}
|
||||
out := make(map[string]string, len(tags))
|
||||
for k, v := range tags {
|
||||
if _, ok := allowSet[strings.ToLower(k)]; ok {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// extractPrincipalTags pulls the principal-tags namespace claim out of the
|
||||
// JWT claim map. Only string values survive — everything else is dropped to
|
||||
// avoid surfacing structured data into a flat policy condition key. Returns
|
||||
// nil when the claim is absent or empty.
|
||||
func extractPrincipalTags(claims map[string]interface{}) map[string]string {
|
||||
raw, ok := claims[PrincipalTagsClaim]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
obj, ok := raw.(map[string]interface{})
|
||||
if !ok || len(obj) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]string, len(obj))
|
||||
for k, v := range obj {
|
||||
switch s := v.(type) {
|
||||
case string:
|
||||
out[k] = s
|
||||
case []interface{}:
|
||||
// Multi-value tag: AWS condition keys carry only a single value, so
|
||||
// take the first stringy element. Multi-value matching can land
|
||||
// later if a real customer needs it.
|
||||
for _, e := range s {
|
||||
if str, ok := e.(string); ok {
|
||||
out[k] = str
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// normalizeThumbprints lowercases and de-duplicates the configured allowlist.
|
||||
// Returns a set keyed by lowercase hex for O(1) lookup during TLS verification.
|
||||
func normalizeThumbprints(in []string) map[string]struct{} {
|
||||
out := make(map[string]struct{}, len(in))
|
||||
for _, t := range in {
|
||||
t = strings.ToLower(strings.TrimSpace(t))
|
||||
if t == "" {
|
||||
continue
|
||||
}
|
||||
out[t] = struct{}{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// verifyThumbprintMatch checks that some certificate in the negotiated chain
|
||||
// hashes to a thumbprint in `expected`. AWS pins the certificate immediately
|
||||
// below the root in the chain; we accept any chain certificate to also cover
|
||||
// self-signed deployments and skip-verify test setups. When the chain has not
|
||||
// been built (InsecureSkipVerify), we fall back to PeerCertificates.
|
||||
func verifyThumbprintMatch(cs tls.ConnectionState, expected map[string]struct{}) error {
|
||||
candidates := collectThumbprintCandidates(cs)
|
||||
for _, c := range candidates {
|
||||
sum := sha1.Sum(c.Raw)
|
||||
hexSum := hex.EncodeToString(sum[:])
|
||||
if _, ok := expected[hexSum]; ok {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("OIDC TLS thumbprint did not match any configured allowlist entry")
|
||||
}
|
||||
|
||||
// collectThumbprintCandidates flattens the verified chains and peer cert list
|
||||
// into a single slice of unique certificates worth checking.
|
||||
func collectThumbprintCandidates(cs tls.ConnectionState) []*x509.Certificate {
|
||||
var out []*x509.Certificate
|
||||
seen := map[string]struct{}{}
|
||||
add := func(c *x509.Certificate) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
k := string(c.Raw)
|
||||
if _, ok := seen[k]; ok {
|
||||
return
|
||||
}
|
||||
seen[k] = struct{}{}
|
||||
out = append(out, c)
|
||||
}
|
||||
for _, chain := range cs.VerifiedChains {
|
||||
for _, c := range chain {
|
||||
add(c)
|
||||
}
|
||||
}
|
||||
for _, c := range cs.PeerCertificates {
|
||||
add(c)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// JWKS represents JSON Web Key Set
|
||||
type JWKS struct {
|
||||
Keys []JWK `json:"keys"`
|
||||
@@ -145,6 +369,20 @@ func (p *OIDCProvider) Initialize(config interface{}) error {
|
||||
glog.Warningf("OIDC provider %q is configured to skip TLS verification. This is insecure and should not be used in production.", p.name)
|
||||
}
|
||||
|
||||
// Thumbprint pinning: when configured, every TLS handshake to the IDP must
|
||||
// present a chain whose terminal certificate (the cert just below the root,
|
||||
// matching AWS IAM semantics) hashes to one of the listed SHA-1 digests.
|
||||
// VerifyConnection runs after the chain build, so cs.VerifiedChains is
|
||||
// populated when InsecureSkipVerify is false; we additionally pin against
|
||||
// PeerCertificates so self-signed test setups work too.
|
||||
if len(oidcConfig.Thumbprints) > 0 {
|
||||
expected := normalizeThumbprints(oidcConfig.Thumbprints)
|
||||
tlsConfig.VerifyConnection = func(cs tls.ConnectionState) error {
|
||||
return verifyThumbprintMatch(cs, expected)
|
||||
}
|
||||
glog.V(2).Infof("OIDC provider %q: TLS thumbprint pinning enabled (%d allowed)", p.name, len(expected))
|
||||
}
|
||||
|
||||
if oidcConfig.TLSCACert != "" {
|
||||
// Validate that the CA cert path is absolute to prevent reading unintended files
|
||||
if !filepath.IsAbs(oidcConfig.TLSCACert) {
|
||||
@@ -184,7 +422,7 @@ func (p *OIDCProvider) validateConfig(config *OIDCConfig) error {
|
||||
return fmt.Errorf("issuer is required")
|
||||
}
|
||||
|
||||
if config.ClientID == "" {
|
||||
if config.ClientID == "" && len(config.ClientIDs) == 0 {
|
||||
return fmt.Errorf("client ID is required")
|
||||
}
|
||||
|
||||
@@ -196,6 +434,32 @@ func (p *OIDCProvider) validateConfig(config *OIDCConfig) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// allowedAudiences returns the merged list of acceptable audiences for this
|
||||
// provider. Both the singular ClientID and the plural ClientIDs are honoured;
|
||||
// duplicates collapse silently.
|
||||
func (p *OIDCProvider) allowedAudiences() []string {
|
||||
if p.config == nil {
|
||||
return nil
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
var out []string
|
||||
add := func(s string) {
|
||||
if s == "" {
|
||||
return
|
||||
}
|
||||
if _, ok := seen[s]; ok {
|
||||
return
|
||||
}
|
||||
seen[s] = struct{}{}
|
||||
out = append(out, s)
|
||||
}
|
||||
add(p.config.ClientID)
|
||||
for _, c := range p.config.ClientIDs {
|
||||
add(c)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Authenticate authenticates a user with an OIDC token
|
||||
func (p *OIDCProvider) Authenticate(ctx context.Context, token string) (*providers.ExternalIdentity, error) {
|
||||
if !p.initialized {
|
||||
@@ -266,12 +530,15 @@ func (p *OIDCProvider) Authenticate(ctx context.Context, token string) (*provide
|
||||
}
|
||||
|
||||
identity := &providers.ExternalIdentity{
|
||||
UserID: claims.Subject,
|
||||
Email: email,
|
||||
DisplayName: displayName,
|
||||
Groups: groups,
|
||||
Attributes: attributes,
|
||||
Provider: p.name,
|
||||
UserID: claims.Subject,
|
||||
Email: email,
|
||||
DisplayName: displayName,
|
||||
Groups: groups,
|
||||
Attributes: attributes,
|
||||
Provider: p.name,
|
||||
Issuer: claims.Issuer,
|
||||
PrincipalTags: filterPrincipalTags(extractPrincipalTags(claims.Claims), p.config.AllowedPrincipalTagKeys),
|
||||
ClaimPolicies: extractClaimPolicies(claims.Claims, p.config.PolicyClaim),
|
||||
}
|
||||
|
||||
// Pass the token expiration to limit session duration
|
||||
@@ -422,33 +689,45 @@ func (p *OIDCProvider) ValidateToken(ctx context.Context, token string) (*provid
|
||||
return nil, fmt.Errorf("%w: expected %s, got %s", providers.ErrProviderInvalidIssuer, p.config.Issuer, issuer)
|
||||
}
|
||||
|
||||
// Check audience claim (aud) or authorized party (azp) - Keycloak uses azp
|
||||
// Per RFC 7519, aud can be either a string or an array of strings
|
||||
// Check audience claim (aud) or authorized party (azp) — Keycloak uses azp.
|
||||
// Per RFC 7519, aud can be either a string or an array of strings.
|
||||
// Multiple client IDs are supported per AWS IAM CreateOpenIDConnectProvider
|
||||
// semantics: any one match in the allowlist accepts the token.
|
||||
allowed := p.allowedAudiences()
|
||||
allowedSet := make(map[string]struct{}, len(allowed))
|
||||
for _, a := range allowed {
|
||||
allowedSet[a] = struct{}{}
|
||||
}
|
||||
|
||||
var audienceMatched bool
|
||||
if audClaim, ok := claims["aud"]; ok {
|
||||
switch aud := audClaim.(type) {
|
||||
case string:
|
||||
if aud == p.config.ClientID {
|
||||
if _, ok := allowedSet[aud]; ok {
|
||||
audienceMatched = true
|
||||
}
|
||||
case []interface{}:
|
||||
for _, a := range aud {
|
||||
if str, ok := a.(string); ok && str == p.config.ClientID {
|
||||
audienceMatched = true
|
||||
break
|
||||
if str, ok := a.(string); ok {
|
||||
if _, ok := allowedSet[str]; ok {
|
||||
audienceMatched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !audienceMatched {
|
||||
if azp, ok := claims["azp"].(string); ok && azp == p.config.ClientID {
|
||||
audienceMatched = true
|
||||
if azp, ok := claims["azp"].(string); ok {
|
||||
if _, ok := allowedSet[azp]; ok {
|
||||
audienceMatched = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !audienceMatched {
|
||||
return nil, fmt.Errorf("%w: expected client ID %s", providers.ErrProviderInvalidAudience, p.config.ClientID)
|
||||
return nil, fmt.Errorf("%w: token audience matches none of the configured client IDs", providers.ErrProviderInvalidAudience)
|
||||
}
|
||||
|
||||
subject, ok := claims["sub"].(string)
|
||||
@@ -550,39 +829,169 @@ func (p *OIDCProvider) mapClaimsToRolesWithConfig(claims *providers.TokenClaims)
|
||||
return roles
|
||||
}
|
||||
|
||||
// getPublicKey retrieves the public key for the given key ID from JWKS
|
||||
// getPublicKey retrieves the public key for the given key ID from JWKS.
|
||||
// Cache hits use the read lock so concurrent token validations don't
|
||||
// serialize on JWKS lookup. Misses and expirations promote to the write
|
||||
// lock so the JWKS fetch + cache write happens once per refresh cycle.
|
||||
func (p *OIDCProvider) getPublicKey(ctx context.Context, kid string) (interface{}, error) {
|
||||
// Fetch JWKS if not cached or refresh if expired
|
||||
if p.jwksCache == nil || (!p.jwksFetchedAt.IsZero() && time.Since(p.jwksFetchedAt) > p.jwksTTL) {
|
||||
if err := p.fetchJWKS(ctx); err != nil {
|
||||
// Fast path: read lock and look in cache.
|
||||
p.mu.RLock()
|
||||
if p.jwksCache != nil && (p.jwksFetchedAt.IsZero() || time.Since(p.jwksFetchedAt) <= p.jwksTTL) {
|
||||
for _, key := range p.jwksCache.Keys {
|
||||
if key.Kid == kid {
|
||||
k := key
|
||||
p.mu.RUnlock()
|
||||
return p.parseJWK(&k)
|
||||
}
|
||||
}
|
||||
}
|
||||
p.mu.RUnlock()
|
||||
|
||||
// Slow path: take the write lock for the (re)fetch + retry. Re-check the
|
||||
// cache under the write lock in case another goroutine already refreshed.
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
cacheValid := p.jwksCache != nil && (p.jwksFetchedAt.IsZero() || time.Since(p.jwksFetchedAt) <= p.jwksTTL)
|
||||
if !cacheValid {
|
||||
if err := p.fetchJWKSLocked(ctx); err != nil {
|
||||
return nil, fmt.Errorf("failed to fetch JWKS: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Find the key with matching kid
|
||||
for _, key := range p.jwksCache.Keys {
|
||||
if key.Kid == kid {
|
||||
return p.parseJWK(&key)
|
||||
k := key
|
||||
return p.parseJWK(&k)
|
||||
}
|
||||
}
|
||||
|
||||
// Key not found in cache. Refresh JWKS once to handle key rotation and retry.
|
||||
if err := p.fetchJWKS(ctx); err != nil {
|
||||
// Key not found in cache. Refresh JWKS once to handle key rotation.
|
||||
if err := p.fetchJWKSLocked(ctx); err != nil {
|
||||
return nil, fmt.Errorf("failed to refresh JWKS after key miss: %v", err)
|
||||
}
|
||||
for _, key := range p.jwksCache.Keys {
|
||||
if key.Kid == kid {
|
||||
return p.parseJWK(&key)
|
||||
k := key
|
||||
return p.parseJWK(&k)
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("key with ID %s not found in JWKS after refresh", kid)
|
||||
}
|
||||
|
||||
// fetchJWKS fetches the JWKS from the provider
|
||||
// discoveryDocument is the subset of the OpenID Provider Configuration we need.
|
||||
// See https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata.
|
||||
type discoveryDocument struct {
|
||||
Issuer string `json:"issuer"`
|
||||
JWKSUri string `json:"jwks_uri"`
|
||||
}
|
||||
|
||||
// resolveJWKSUriLocked determines the JWKS URI for the provider. The caller
|
||||
// must hold p.mu (write lock); the function reads/writes p.resolvedJWKSUri
|
||||
// and p.discoveryFailed without taking the lock itself.
|
||||
//
|
||||
// Order of resolution:
|
||||
// 1. explicit config.JWKSUri (operator override; never overridden by discovery).
|
||||
// 2. cached resolvedJWKSUri from a prior discovery (refreshed when JWKS cache expires).
|
||||
// 3. .well-known/openid-configuration discovery (per OIDC Discovery 1.0).
|
||||
// 4. fallback to {issuer}/.well-known/jwks.json (compat path for IDPs that
|
||||
// don't publish discovery).
|
||||
func (p *OIDCProvider) resolveJWKSUriLocked(ctx context.Context) (string, error) {
|
||||
if p.config.JWKSUri != "" {
|
||||
return p.config.JWKSUri, nil
|
||||
}
|
||||
if p.resolvedJWKSUri != "" {
|
||||
return p.resolvedJWKSUri, nil
|
||||
}
|
||||
|
||||
issuer := strings.TrimSuffix(p.config.Issuer, "/")
|
||||
|
||||
if !p.discoveryFailed {
|
||||
discoveryURL := issuer + "/.well-known/openid-configuration"
|
||||
uri, err := p.fetchDiscoveryJWKSUri(ctx, discoveryURL)
|
||||
switch {
|
||||
case err == nil:
|
||||
p.resolvedJWKSUri = uri
|
||||
return uri, nil
|
||||
default:
|
||||
// Cache the failure so we don't pay the discovery RTT on every refresh.
|
||||
// Operators with non-discovery IDPs see one failed lookup at startup.
|
||||
glog.V(3).Infof("OIDC discovery at %s failed (%v); falling back to /.well-known/jwks.json", discoveryURL, err)
|
||||
p.discoveryFailed = true
|
||||
}
|
||||
}
|
||||
|
||||
return issuer + "/.well-known/jwks.json", nil
|
||||
}
|
||||
|
||||
// fetchDiscoveryJWKSUri retrieves the OIDC discovery document and returns
|
||||
// the jwks_uri field. The issuer claim in the document must match config.Issuer
|
||||
// to defend against issuer-substitution attacks during discovery.
|
||||
func (p *OIDCProvider) fetchDiscoveryJWKSUri(ctx context.Context, discoveryURL string) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", discoveryURL, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create discovery request: %v", err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := p.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("fetch discovery document: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("discovery endpoint returned status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var doc discoveryDocument
|
||||
if err := json.NewDecoder(resp.Body).Decode(&doc); err != nil {
|
||||
return "", fmt.Errorf("decode discovery document: %v", err)
|
||||
}
|
||||
|
||||
if doc.JWKSUri == "" {
|
||||
return "", fmt.Errorf("discovery document missing jwks_uri")
|
||||
}
|
||||
|
||||
// Issuer must be present and match: a discovery doc that points to a
|
||||
// different issuer is either a misconfiguration or an attack against
|
||||
// issuer-confusion, and a doc that omits the issuer field entirely
|
||||
// would have bypassed the previous check (doc.Issuer != "" guard) and
|
||||
// silently accepted whatever JWKS URI the document supplied. OIDC
|
||||
// Discovery 1.0 §3 mandates the issuer field, so treat missing as a
|
||||
// hard failure. Compare after trimming a single trailing slash on each
|
||||
// side because real IdPs disagree on whether the configured issuer
|
||||
// has one.
|
||||
if strings.TrimSuffix(doc.Issuer, "/") != strings.TrimSuffix(p.config.Issuer, "/") {
|
||||
return "", fmt.Errorf("discovery issuer %q does not match configured issuer %q", doc.Issuer, p.config.Issuer)
|
||||
}
|
||||
|
||||
return doc.JWKSUri, nil
|
||||
}
|
||||
|
||||
// fetchJWKS is a thin wrapper around fetchJWKSLocked that acquires the
|
||||
// write lock. Used by tests; production callers in getPublicKey already
|
||||
// hold the lock and call fetchJWKSLocked directly.
|
||||
func (p *OIDCProvider) fetchJWKS(ctx context.Context) error {
|
||||
jwksURL := p.config.JWKSUri
|
||||
if jwksURL == "" {
|
||||
jwksURL = strings.TrimSuffix(p.config.Issuer, "/") + "/.well-known/jwks.json"
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.fetchJWKSLocked(ctx)
|
||||
}
|
||||
|
||||
// fetchJWKSLocked fetches the JWKS from the provider. The caller must hold
|
||||
// p.mu (write lock); the function writes p.jwksCache and p.jwksFetchedAt
|
||||
// without taking the lock itself.
|
||||
//
|
||||
// Each fetch reattempts discovery if the previous attempt failed: a
|
||||
// transient 5xx that flipped discoveryFailed at startup shouldn't lock the
|
||||
// provider into the fallback path forever. The retry rate is bounded by
|
||||
// the JWKS TTL (typically 1h), so the discovery RTT cost is amortized.
|
||||
func (p *OIDCProvider) fetchJWKSLocked(ctx context.Context) error {
|
||||
if p.config.JWKSUri == "" && p.resolvedJWKSUri == "" {
|
||||
p.discoveryFailed = false
|
||||
}
|
||||
jwksURL, err := p.resolveJWKSUriLocked(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve JWKS URI: %v", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", jwksURL, nil)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExtractClaimPoliciesString(t *testing.T) {
|
||||
got := extractClaimPolicies(map[string]interface{}{"policy": "readonly"}, "policy")
|
||||
if !reflect.DeepEqual(got, []string{"readonly"}) {
|
||||
t.Fatalf("got=%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractClaimPoliciesCommaSeparated(t *testing.T) {
|
||||
got := extractClaimPolicies(map[string]interface{}{"policy": "readonly, billing , "}, "policy")
|
||||
if !reflect.DeepEqual(got, []string{"readonly", "billing"}) {
|
||||
t.Fatalf("got=%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractClaimPoliciesArray(t *testing.T) {
|
||||
got := extractClaimPolicies(map[string]interface{}{
|
||||
"policy": []interface{}{"readonly", "billing", 42, ""}, // non-string + empty filtered
|
||||
}, "policy")
|
||||
if !reflect.DeepEqual(got, []string{"readonly", "billing"}) {
|
||||
t.Fatalf("got=%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractClaimPoliciesMissing(t *testing.T) {
|
||||
if got := extractClaimPolicies(map[string]interface{}{}, "policy"); got != nil {
|
||||
t.Fatalf("expected nil, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractClaimPoliciesEmptyClaimName(t *testing.T) {
|
||||
// Provider not in claim-mode -> never read the claim, even if present.
|
||||
if got := extractClaimPolicies(map[string]interface{}{"policy": "readonly"}, ""); got != nil {
|
||||
t.Fatalf("empty claim name should return nil, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractClaimPoliciesUnsupportedShape(t *testing.T) {
|
||||
// Numeric / object / bool values should be ignored, not panic.
|
||||
cases := []interface{}{
|
||||
42,
|
||||
3.14,
|
||||
map[string]interface{}{"x": "y"},
|
||||
true,
|
||||
}
|
||||
for _, v := range cases {
|
||||
if got := extractClaimPolicies(map[string]interface{}{"policy": v}, "policy"); got != nil {
|
||||
t.Fatalf("value %v: expected nil, got %v", v, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExtractPrincipalTagsObjectShape(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
PrincipalTagsClaim: map[string]interface{}{
|
||||
"team": "infra",
|
||||
"env": "prod",
|
||||
"empty": "",
|
||||
// non-string values are dropped
|
||||
"count": 42,
|
||||
},
|
||||
}
|
||||
got := extractPrincipalTags(claims)
|
||||
want := map[string]string{"team": "infra", "env": "prod", "empty": ""}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got=%v want=%v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractPrincipalTagsArrayValueTakesFirst(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
PrincipalTagsClaim: map[string]interface{}{
|
||||
"team": []interface{}{"infra", "ignored"},
|
||||
},
|
||||
}
|
||||
got := extractPrincipalTags(claims)
|
||||
if got["team"] != "infra" {
|
||||
t.Fatalf("expected first array element, got %q", got["team"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractPrincipalTagsAbsent(t *testing.T) {
|
||||
if got := extractPrincipalTags(map[string]interface{}{}); got != nil {
|
||||
t.Fatalf("expected nil for missing claim, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractPrincipalTagsWrongShape(t *testing.T) {
|
||||
claims := map[string]interface{}{PrincipalTagsClaim: "not-an-object"}
|
||||
if got := extractPrincipalTags(claims); got != nil {
|
||||
t.Fatalf("expected nil for non-object claim, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterPrincipalTagsAllowlist(t *testing.T) {
|
||||
in := map[string]string{"team": "infra", "env": "prod", "secret": "shh"}
|
||||
|
||||
t.Run("empty allowlist denies all", func(t *testing.T) {
|
||||
if got := filterPrincipalTags(in, nil); got != nil {
|
||||
t.Fatalf("expected nil, got %v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("partial allowlist", func(t *testing.T) {
|
||||
got := filterPrincipalTags(in, []string{"team", "env"})
|
||||
want := map[string]string{"team": "infra", "env": "prod"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got=%v want=%v", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("allowlist with no matches", func(t *testing.T) {
|
||||
if got := filterPrincipalTags(in, []string{"unknown"}); got != nil {
|
||||
t.Fatalf("expected nil, got %v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("case-insensitive on key", func(t *testing.T) {
|
||||
// AWS session tag keys are case-insensitive. An IDP whose claim
|
||||
// uses different casing than the operator's allowlist string
|
||||
// must still match.
|
||||
got := filterPrincipalTags(map[string]string{"Team": "infra"}, []string{"TEAM"})
|
||||
want := map[string]string{"Team": "infra"} // original casing preserved on output
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got=%v want=%v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// thumbprintFromTLS returns the SHA-1 hex of the first peer certificate the
|
||||
// given TLS server presents. It mirrors the pinning algorithm used by the
|
||||
// OIDC provider so the test is hashing the cert that will actually be
|
||||
// verified at runtime.
|
||||
func thumbprintFromTLS(t *testing.T, server *httptest.Server) string {
|
||||
t.Helper()
|
||||
if server.TLS == nil || len(server.Certificate().Raw) == 0 {
|
||||
t.Fatal("server has no TLS certificate")
|
||||
}
|
||||
sum := sha1.Sum(server.Certificate().Raw)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// newTLSIDP starts a TLS-only test IDP that always serves a static JWKS.
|
||||
// httptest TLS servers use a self-signed certificate by default, which means
|
||||
// callers who want a successful handshake must either trust that cert or
|
||||
// use TLSInsecureSkipVerify.
|
||||
func newTLSIDP(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/jwks.json", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(JWKS{Keys: []JWK{{Kty: "RSA", Kid: "k1", Use: "sig", Alg: "RS256", N: "AQAB", E: "AQAB"}}})
|
||||
})
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.NotFound(w, r) // force fallback path
|
||||
})
|
||||
server := httptest.NewTLSServer(mux)
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
|
||||
// pinnedProvider configures an OIDC provider that pins TLS to the given
|
||||
// thumbprint allowlist and trusts only the test server's self-signed cert.
|
||||
func pinnedProvider(t *testing.T, server *httptest.Server, thumbprints []string) *OIDCProvider {
|
||||
t.Helper()
|
||||
p := NewOIDCProvider("thumbprint-test")
|
||||
cfg := &OIDCConfig{
|
||||
Issuer: server.URL,
|
||||
ClientID: "anything",
|
||||
Thumbprints: thumbprints,
|
||||
TLSInsecureSkipVerify: true, // we're doing the trust decision via thumbprint
|
||||
}
|
||||
if err := p.Initialize(cfg); err != nil {
|
||||
t.Fatalf("Initialize: %v", err)
|
||||
}
|
||||
// Replace the inner transport's RootCAs with the server's cert so the chain
|
||||
// builder also accepts it; this exercises the verified-chain path.
|
||||
if transport, ok := p.httpClient.Transport.(*http.Transport); ok && transport.TLSClientConfig != nil {
|
||||
transport.TLSClientConfig.InsecureSkipVerify = false
|
||||
transport.TLSClientConfig.RootCAs = server.Client().Transport.(*http.Transport).TLSClientConfig.RootCAs
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func TestThumbprintMatchAccepted(t *testing.T) {
|
||||
server := newTLSIDP(t)
|
||||
tp := thumbprintFromTLS(t, server)
|
||||
p := pinnedProvider(t, server, []string{tp})
|
||||
|
||||
if err := p.fetchJWKS(context.Background()); err != nil {
|
||||
t.Fatalf("fetchJWKS with matching thumbprint should succeed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestThumbprintMismatchRejected(t *testing.T) {
|
||||
server := newTLSIDP(t)
|
||||
// Flip the last byte so the digest can't match anything legitimate.
|
||||
bad := "0000000000000000000000000000000000000000"
|
||||
p := pinnedProvider(t, server, []string{bad})
|
||||
|
||||
err := p.fetchJWKS(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("fetchJWKS with mismatched thumbprint should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestThumbprintAllowlistAcceptsMixedCase(t *testing.T) {
|
||||
server := newTLSIDP(t)
|
||||
tp := thumbprintFromTLS(t, server)
|
||||
// Mix uppercase + whitespace to ensure normalization is applied.
|
||||
p := pinnedProvider(t, server, []string{" " + uppercase(tp) + " "})
|
||||
if err := p.fetchJWKS(context.Background()); err != nil {
|
||||
t.Fatalf("normalized thumbprint should match: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// uppercase returns s with letters uppercased — cheap helper avoiding a
|
||||
// dependency on strings.ToUpper at the package level for clarity.
|
||||
func uppercase(s string) string {
|
||||
out := make([]byte, len(s))
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 'a' && c <= 'z' {
|
||||
c -= 32
|
||||
}
|
||||
out[i] = c
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
// guard against a future refactor that drops VerifyConnection by checking
|
||||
// that omitting Thumbprints leaves the connection unverified-by-pin.
|
||||
func TestThumbprintEmptyAllowlistSkipsCheck(t *testing.T) {
|
||||
server := newTLSIDP(t)
|
||||
p := pinnedProvider(t, server, nil)
|
||||
transport, ok := p.httpClient.Transport.(*http.Transport)
|
||||
if !ok {
|
||||
t.Fatal("expected *http.Transport")
|
||||
}
|
||||
if transport.TLSClientConfig.VerifyConnection != nil {
|
||||
t.Fatal("VerifyConnection must be nil when no thumbprints are configured")
|
||||
}
|
||||
// And the full TLS handshake still succeeds normally.
|
||||
if err := p.fetchJWKS(context.Background()); err != nil {
|
||||
t.Fatalf("fetchJWKS with no thumbprints: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure the underlying tls.Config still rejects truly invalid handshakes
|
||||
// when InsecureSkipVerify is on but no thumbprint allowlist is configured —
|
||||
// in that case we explicitly want to *trust* the connection (skip-verify),
|
||||
// just as the existing test code did.
|
||||
func TestThumbprintSkipVerifyHonoured(t *testing.T) {
|
||||
server := newTLSIDP(t)
|
||||
p := NewOIDCProvider("skip")
|
||||
if err := p.Initialize(&OIDCConfig{
|
||||
Issuer: server.URL,
|
||||
ClientID: "x",
|
||||
TLSInsecureSkipVerify: true,
|
||||
}); err != nil {
|
||||
t.Fatalf("Initialize: %v", err)
|
||||
}
|
||||
transport := p.httpClient.Transport.(*http.Transport)
|
||||
if !transport.TLSClientConfig.InsecureSkipVerify {
|
||||
t.Fatal("InsecureSkipVerify should be set")
|
||||
}
|
||||
if got := transport.TLSClientConfig.MinVersion; got != tls.VersionTLS12 {
|
||||
t.Fatalf("MinVersion = %v want TLS12", got)
|
||||
}
|
||||
}
|
||||
@@ -48,16 +48,19 @@ var (
|
||||
|
||||
// isSafePolicyVariable reports whether a policy variable may be substituted
|
||||
// with a value from RequestContext. The fixed allowlist covers AWS-defined
|
||||
// variables; any jwt:/saml:/oidc: claim is also allowed because those come
|
||||
// from a validated identity token (the STS session JWT or federated assertion)
|
||||
// and the claim set is controlled by the trusted identity provider.
|
||||
// variables; any jwt:/saml:/oidc:/aws:PrincipalTag/ claim is also allowed
|
||||
// because those come from a validated identity token (the STS session JWT
|
||||
// or federated assertion) and the claim set is controlled by the trusted
|
||||
// identity provider.
|
||||
func isSafePolicyVariable(variable string) bool {
|
||||
if safePolicyVariables[variable] {
|
||||
return true
|
||||
}
|
||||
return strings.HasPrefix(variable, "jwt:") ||
|
||||
strings.HasPrefix(variable, "saml:") ||
|
||||
strings.HasPrefix(variable, "oidc:")
|
||||
strings.HasPrefix(variable, "oidc:") ||
|
||||
strings.HasPrefix(variable, "aws:PrincipalTag/") ||
|
||||
strings.HasPrefix(variable, "aws:RequestTag/")
|
||||
}
|
||||
|
||||
// PolicyEngine evaluates policies against requests
|
||||
|
||||
@@ -49,6 +49,22 @@ type ExternalIdentity struct {
|
||||
// Provider is the name of the identity provider
|
||||
Provider string `json:"provider"`
|
||||
|
||||
// Issuer is the OIDC `iss` claim (or equivalent) from the source token.
|
||||
// Stable per (provider, identity) and used together with UserID to derive
|
||||
// a stable parent-user hash that survives token rotation.
|
||||
Issuer string `json:"issuer,omitempty"`
|
||||
|
||||
// PrincipalTags are key/value pairs extracted from the AWS principal-tags
|
||||
// namespace claim (`https://aws.amazon.com/tags/principal_tags`). They are
|
||||
// surfaced as `aws:PrincipalTag/<key>` in the policy request context
|
||||
// (subject to per-provider allowlist filtering at the STS layer).
|
||||
PrincipalTags map[string]string `json:"principalTags,omitempty"`
|
||||
|
||||
// ClaimPolicies are policy names pulled from the provider-configured
|
||||
// PolicyClaim. Empty when the provider isn't running in claim-based
|
||||
// policy mode or the claim was absent.
|
||||
ClaimPolicies []string `json:"claimPolicies,omitempty"`
|
||||
|
||||
// TokenExpiration is the expiration time of the source identity token
|
||||
// This is used to limit session duration to not exceed the token's exp claim
|
||||
TokenExpiration *time.Time `json:"tokenExpiration,omitempty"`
|
||||
|
||||
@@ -13,6 +13,85 @@ type CommonResponse struct {
|
||||
} `xml:"ResponseMetadata"`
|
||||
}
|
||||
|
||||
// IAMTag mirrors AWS IAM's Tag list element with the Key/Value pair shape.
|
||||
type IAMTag struct {
|
||||
Key string `xml:"Key"`
|
||||
Value string `xml:"Value"`
|
||||
}
|
||||
|
||||
// OpenIDConnectProviderListEntry is one element of ListOpenIDConnectProviders.
|
||||
type OpenIDConnectProviderListEntry struct {
|
||||
Arn string `xml:"Arn"`
|
||||
}
|
||||
|
||||
// ListOpenIDConnectProvidersResponse is the response for ListOpenIDConnectProviders.
|
||||
type ListOpenIDConnectProvidersResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ ListOpenIDConnectProvidersResponse"`
|
||||
ListOpenIDConnectProvidersResult struct {
|
||||
OpenIDConnectProviderList []*OpenIDConnectProviderListEntry `xml:"OpenIDConnectProviderList>member"`
|
||||
} `xml:"ListOpenIDConnectProvidersResult"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// GetOpenIDConnectProviderResponse is the response for GetOpenIDConnectProvider.
|
||||
type GetOpenIDConnectProviderResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ GetOpenIDConnectProviderResponse"`
|
||||
GetOpenIDConnectProviderResult struct {
|
||||
Url string `xml:"Url"`
|
||||
ClientIDList []string `xml:"ClientIDList>member,omitempty"`
|
||||
ThumbprintList []string `xml:"ThumbprintList>member,omitempty"`
|
||||
Tags []*IAMTag `xml:"Tags>member,omitempty"`
|
||||
CreateDate string `xml:"CreateDate,omitempty"`
|
||||
} `xml:"GetOpenIDConnectProviderResult"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// CreateOpenIDConnectProviderResponse is the response for CreateOpenIDConnectProvider.
|
||||
type CreateOpenIDConnectProviderResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ CreateOpenIDConnectProviderResponse"`
|
||||
CreateOpenIDConnectProviderResult struct {
|
||||
OpenIDConnectProviderArn string `xml:"OpenIDConnectProviderArn"`
|
||||
Tags []*IAMTag `xml:"Tags>member,omitempty"`
|
||||
} `xml:"CreateOpenIDConnectProviderResult"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// DeleteOpenIDConnectProviderResponse is the response for DeleteOpenIDConnectProvider.
|
||||
type DeleteOpenIDConnectProviderResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ DeleteOpenIDConnectProviderResponse"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// AddClientIDToOpenIDConnectProviderResponse is the response for AddClientIDToOpenIDConnectProvider.
|
||||
type AddClientIDToOpenIDConnectProviderResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ AddClientIDToOpenIDConnectProviderResponse"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// RemoveClientIDFromOpenIDConnectProviderResponse is the response for RemoveClientIDFromOpenIDConnectProvider.
|
||||
type RemoveClientIDFromOpenIDConnectProviderResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ RemoveClientIDFromOpenIDConnectProviderResponse"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// UpdateOpenIDConnectProviderThumbprintResponse is the response for UpdateOpenIDConnectProviderThumbprint.
|
||||
type UpdateOpenIDConnectProviderThumbprintResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ UpdateOpenIDConnectProviderThumbprintResponse"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// TagOpenIDConnectProviderResponse is the response for TagOpenIDConnectProvider.
|
||||
type TagOpenIDConnectProviderResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ TagOpenIDConnectProviderResponse"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// UntagOpenIDConnectProviderResponse is the response for UntagOpenIDConnectProvider.
|
||||
type UntagOpenIDConnectProviderResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ UntagOpenIDConnectProviderResponse"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// SetRequestId stores the request ID generated for the current HTTP request.
|
||||
func (r *CommonResponse) SetRequestId(requestID string) {
|
||||
r.ResponseMetadata.RequestId = requestID
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package sts
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestIsClaimBasedPolicyRoleArn(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
arn string
|
||||
want bool
|
||||
}{
|
||||
{"empty matches", "", true},
|
||||
{"sentinel matches", ClaimBasedPolicyRoleArn, true},
|
||||
{"concrete role does not", "arn:aws:iam::123:role/admin", false},
|
||||
{"random ARN does not", "arn:aws:sts::123:assumed-role/X/Y", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := IsClaimBasedPolicyRoleArn(tc.arn); got != tc.want {
|
||||
t.Fatalf("got=%v want=%v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,10 @@ const (
|
||||
ConfigFieldBasePath = "basePath"
|
||||
ConfigFieldIssuer = "issuer"
|
||||
ConfigFieldClientID = "clientId"
|
||||
ConfigFieldClientIDs = "clientIds"
|
||||
ConfigFieldThumbprints = "thumbprints"
|
||||
ConfigFieldAllowedPrincipalTagKeys = "allowedPrincipalTagKeys"
|
||||
ConfigFieldPolicyClaim = "policyClaim"
|
||||
ConfigFieldClientSecret = "clientSecret"
|
||||
ConfigFieldJWKSUri = "jwksUri"
|
||||
ConfigFieldScopes = "scopes"
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package sts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/providers"
|
||||
)
|
||||
|
||||
// stubIdentityProvider is the minimal IdentityProvider needed to drive
|
||||
// lookupOIDCProviderForAccount; the lookup never calls Authenticate.
|
||||
type stubIdentityProvider struct{ name string }
|
||||
|
||||
func (s *stubIdentityProvider) Name() string { return s.name }
|
||||
func (s *stubIdentityProvider) Initialize(interface{}) error { return nil }
|
||||
func (s *stubIdentityProvider) Authenticate(context.Context, string) (*providers.ExternalIdentity, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (s *stubIdentityProvider) GetUserInfo(context.Context, string) (*providers.ExternalIdentity, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (s *stubIdentityProvider) ValidateToken(context.Context, string) (*providers.TokenClaims, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestLookupOIDCProviderForAccountPrefersAccountMatch(t *testing.T) {
|
||||
const issuer = "https://example.com"
|
||||
accountA := &stubIdentityProvider{name: "A"}
|
||||
accountB := &stubIdentityProvider{name: "B"}
|
||||
|
||||
s := &STSService{issuerToProvider: map[string]providers.IdentityProvider{}}
|
||||
s.SetIAMManagedOIDCProviders(map[string][]ScopedOIDCProvider{
|
||||
issuer: {
|
||||
{AccountID: "111111111111", Provider: accountA},
|
||||
{AccountID: "222222222222", Provider: accountB},
|
||||
},
|
||||
})
|
||||
|
||||
got, ok := s.lookupOIDCProviderForAccount(issuer, "222222222222")
|
||||
if !ok || got != accountB {
|
||||
t.Fatalf("expected accountB provider for matching account, got %v ok=%v", got, ok)
|
||||
}
|
||||
got, ok = s.lookupOIDCProviderForAccount(issuer, "111111111111")
|
||||
if !ok || got != accountA {
|
||||
t.Fatalf("expected accountA provider for matching account, got %v ok=%v", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupOIDCProviderForAccountFallsBackToGlobal(t *testing.T) {
|
||||
const issuer = "https://example.com"
|
||||
global := &stubIdentityProvider{name: "global"}
|
||||
accountA := &stubIdentityProvider{name: "A"}
|
||||
|
||||
s := &STSService{issuerToProvider: map[string]providers.IdentityProvider{}}
|
||||
s.SetIAMManagedOIDCProviders(map[string][]ScopedOIDCProvider{
|
||||
issuer: {
|
||||
{AccountID: "", Provider: global},
|
||||
{AccountID: "111111111111", Provider: accountA},
|
||||
},
|
||||
})
|
||||
|
||||
// Account not represented in records → global match.
|
||||
got, ok := s.lookupOIDCProviderForAccount(issuer, "999999999999")
|
||||
if !ok || got != global {
|
||||
t.Fatalf("expected global provider as fallback, got %v ok=%v", got, ok)
|
||||
}
|
||||
// Empty account hint → never picks an account-scoped record arbitrarily;
|
||||
// only the global record is eligible.
|
||||
got, ok = s.lookupOIDCProviderForAccount(issuer, "")
|
||||
if !ok || got != global {
|
||||
t.Fatalf("expected global provider when account unknown, got %v ok=%v", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupOIDCProviderForAccountSkipsAccountSpecificWhenAccountUnknown(t *testing.T) {
|
||||
const issuer = "https://example.com"
|
||||
accountA := &stubIdentityProvider{name: "A"}
|
||||
|
||||
s := &STSService{issuerToProvider: map[string]providers.IdentityProvider{}}
|
||||
s.SetIAMManagedOIDCProviders(map[string][]ScopedOIDCProvider{
|
||||
issuer: {
|
||||
{AccountID: "111111111111", Provider: accountA},
|
||||
},
|
||||
})
|
||||
|
||||
// No account hint AND no global record → must fall through (return false),
|
||||
// not silently pick the account-A entry. Picking an arbitrary entry is the
|
||||
// pre-fix bug that lets a token be validated by the wrong tenant's record.
|
||||
if _, ok := s.lookupOIDCProviderForAccount(issuer, ""); ok {
|
||||
t.Fatalf("expected no match when account unknown and only account-scoped records exist")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupOIDCProviderForAccountFallsBackToStatic(t *testing.T) {
|
||||
const issuer = "https://example.com"
|
||||
static := &stubIdentityProvider{name: "static"}
|
||||
|
||||
s := &STSService{issuerToProvider: map[string]providers.IdentityProvider{issuer: static}}
|
||||
s.SetIAMManagedOIDCProviders(nil)
|
||||
|
||||
got, ok := s.lookupOIDCProviderForAccount(issuer, "111111111111")
|
||||
if !ok || got != static {
|
||||
t.Fatalf("expected static-config provider as last resort, got %v ok=%v", got, ok)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package sts
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestComputeParentUserStability(t *testing.T) {
|
||||
// Same (sub, iss) must produce the same hash, regardless of order or
|
||||
// whitespace mutations callers should never apply.
|
||||
a := ComputeParentUser("alice", "https://idp.example/")
|
||||
b := ComputeParentUser("alice", "https://idp.example/")
|
||||
if a == "" {
|
||||
t.Fatal("parent user should not be empty for non-empty sub")
|
||||
}
|
||||
if a != b {
|
||||
t.Fatalf("expected stable hash, got %q vs %q", a, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestComputeParentUserDistinguishesIssuer(t *testing.T) {
|
||||
// The point of incorporating iss is that the same `sub` from two providers
|
||||
// must not collide. If this assertion ever fails, the hash input is wrong.
|
||||
a := ComputeParentUser("alice", "https://idp-a.example/")
|
||||
b := ComputeParentUser("alice", "https://idp-b.example/")
|
||||
if a == b {
|
||||
t.Fatalf("hashes for different issuers must differ, both = %q", a)
|
||||
}
|
||||
}
|
||||
|
||||
func TestComputeParentUserDistinguishesSubject(t *testing.T) {
|
||||
a := ComputeParentUser("alice", "https://idp.example/")
|
||||
b := ComputeParentUser("bob", "https://idp.example/")
|
||||
if a == b {
|
||||
t.Fatalf("hashes for different subjects must differ, both = %q", a)
|
||||
}
|
||||
}
|
||||
|
||||
func TestComputeParentUserEmptySub(t *testing.T) {
|
||||
if got := ComputeParentUser("", "https://idp.example/"); got != "" {
|
||||
t.Fatalf("empty sub should produce empty parent user, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestComputeParentUserEmptyIss(t *testing.T) {
|
||||
// Without an issuer, two different IDPs that both name a user "alice"
|
||||
// would collide on the same parent_user. Refuse rather than hash.
|
||||
if got := ComputeParentUser("alice", ""); got != "" {
|
||||
t.Fatalf("empty iss should produce empty parent user, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestComputeParentUserEncoding(t *testing.T) {
|
||||
got := ComputeParentUser("alice", "https://idp.example/")
|
||||
// Base64 RawURL has no padding and uses URL-safe alphabet — important
|
||||
// because parent_user shows up in filer paths and audit log fields.
|
||||
if strings.ContainsAny(got, "=+/") {
|
||||
t.Fatalf("parent user should be base64 raw url, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionClaimsRoundTripParentUser(t *testing.T) {
|
||||
parent := ComputeParentUser("alice", "https://idp.example/")
|
||||
claims := NewSTSSessionClaims("sid-1", "issuer", time.Now().Add(time.Hour)).
|
||||
WithRoleInfo("arn:aws:iam::123:role/r", "arn:aws:sts::123:assumed-role/r/s", "arn:aws:sts::123:assumed-role/r/s").
|
||||
WithParentUser(parent)
|
||||
|
||||
info := claims.ToSessionInfo()
|
||||
if info.ParentUser != parent {
|
||||
t.Fatalf("ParentUser lost on round-trip: got %q want %q", info.ParentUser, parent)
|
||||
}
|
||||
}
|
||||
@@ -91,9 +91,20 @@ func (f *ProviderFactory) convertToOIDCConfig(configMap map[string]interface{})
|
||||
return nil, fmt.Errorf(ErrIssuerRequired)
|
||||
}
|
||||
|
||||
if clientID, ok := configMap[ConfigFieldClientID].(string); ok {
|
||||
clientIDPresent := false
|
||||
if clientID, ok := configMap[ConfigFieldClientID].(string); ok && clientID != "" {
|
||||
config.ClientID = clientID
|
||||
} else {
|
||||
clientIDPresent = true
|
||||
}
|
||||
// Accept the AWS-compatible plural form. Either field satisfies the
|
||||
// "at least one client id" requirement; both can be set together.
|
||||
if rawList, ok := configMap[ConfigFieldClientIDs]; ok {
|
||||
if list, err := f.convertToStringSlice(rawList); err == nil && len(list) > 0 {
|
||||
config.ClientIDs = list
|
||||
clientIDPresent = true
|
||||
}
|
||||
}
|
||||
if !clientIDPresent {
|
||||
return nil, fmt.Errorf(ErrClientIDRequired)
|
||||
}
|
||||
|
||||
@@ -123,6 +134,22 @@ func (f *ProviderFactory) convertToOIDCConfig(configMap map[string]interface{})
|
||||
config.TLSCACert = tlsCaCert
|
||||
}
|
||||
|
||||
if rawThumbprints, ok := configMap[ConfigFieldThumbprints]; ok {
|
||||
if list, err := f.convertToStringSlice(rawThumbprints); err == nil {
|
||||
config.Thumbprints = list
|
||||
}
|
||||
}
|
||||
|
||||
if rawAllowed, ok := configMap[ConfigFieldAllowedPrincipalTagKeys]; ok {
|
||||
if list, err := f.convertToStringSlice(rawAllowed); err == nil {
|
||||
config.AllowedPrincipalTagKeys = list
|
||||
}
|
||||
}
|
||||
|
||||
if policyClaim, ok := configMap[ConfigFieldPolicyClaim].(string); ok {
|
||||
config.PolicyClaim = policyClaim
|
||||
}
|
||||
|
||||
if tlsInsecureSkipVerify, ok := configMap[ConfigFieldTLSInsecureSkipVerify].(bool); ok {
|
||||
config.TLSInsecureSkipVerify = tlsInsecureSkipVerify
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package sts
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -8,6 +10,20 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
// ComputeParentUser returns a stable per-identity hash derived from the OIDC
|
||||
// (sub, iss) tuple. Only the (sub, iss) pair is guaranteed stable across token
|
||||
// refreshes per OpenID Connect Core 1.0 §5.7, so any per-user state (audit
|
||||
// logs, quotas) must key off this value rather than the access-key or session
|
||||
// id. The hash is base64-rawurl-encoded SHA-256 over "openid:<sub>:<iss>" so
|
||||
// it stays filesystem-safe and bounded in length for storage in audit paths.
|
||||
func ComputeParentUser(sub, iss string) string {
|
||||
if sub == "" || iss == "" {
|
||||
return ""
|
||||
}
|
||||
h := sha256.Sum256([]byte("openid:" + sub + ":" + iss))
|
||||
return base64.RawURLEncoding.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// defaultCredentialGenerator is a reusable instance for generating temporary credentials
|
||||
// Reusing a single instance across all calls to ToSessionInfo() reduces allocation overhead
|
||||
// since this method may be called frequently during signature verification
|
||||
@@ -45,6 +61,12 @@ type STSSessionClaims struct {
|
||||
// Session metadata
|
||||
AssumedAt time.Time `json:"assumed_at"` // when role was assumed
|
||||
MaxDuration int64 `json:"max_dur,omitempty"` // maximum session duration in seconds
|
||||
|
||||
// ParentUser is a stable hash of (sub, iss) for tokens minted from an OIDC
|
||||
// identity. It survives token rotation since only the (sub, iss) tuple is
|
||||
// guaranteed stable per OpenID Connect Core 1.0. Empty for non-federated
|
||||
// session types.
|
||||
ParentUser string `json:"puid,omitempty"`
|
||||
}
|
||||
|
||||
// NewSTSSessionClaims creates new STS session claims with all required information
|
||||
@@ -57,6 +79,10 @@ func NewSTSSessionClaims(sessionId, issuer string, expiresAt time.Time) *STSSess
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(expiresAt),
|
||||
NotBefore: jwt.NewNumericDate(now),
|
||||
// jti = sessionId. The session id is already a unique random
|
||||
// identifier, so reusing it as the JWT id avoids a second secret
|
||||
// while still giving the revocation layer a stable lookup key.
|
||||
ID: sessionId,
|
||||
},
|
||||
SessionId: sessionId,
|
||||
TokenType: TokenTypeSession,
|
||||
@@ -96,6 +122,7 @@ func (c *STSSessionClaims) ToSessionInfo() *SessionInfo {
|
||||
ExternalUserId: c.ExternalUserId,
|
||||
ProviderIssuer: c.ProviderIssuer,
|
||||
RequestContext: c.RequestContext,
|
||||
ParentUser: c.ParentUser,
|
||||
// Provide the Subject (sub) from registered claims
|
||||
Subject: c.Subject,
|
||||
Credentials: credentials,
|
||||
@@ -182,3 +209,10 @@ func (c *STSSessionClaims) WithSessionName(sessionName string) *STSSessionClaims
|
||||
c.SessionName = sessionName
|
||||
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 {
|
||||
c.ParentUser = parentUser
|
||||
return c
|
||||
}
|
||||
+196
-22
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
@@ -68,6 +69,21 @@ func (fd FlexibleDuration) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(fd.Duration.String())
|
||||
}
|
||||
|
||||
// ClaimBasedPolicyRoleArn is the AWS-shaped sentinel ARN that callers pass
|
||||
// in the AssumeRoleWithWebIdentity RoleArn field to opt into claim-based
|
||||
// policy resolution. Using a recognisable role-style ARN here (rather than
|
||||
// requiring an empty RoleArn) lets SDKs and AWS CLI builds that always
|
||||
// require RoleArn to be set still reach this code path.
|
||||
const ClaimBasedPolicyRoleArn = "arn:aws:iam:::role/sts-claim-based"
|
||||
|
||||
// IsClaimBasedPolicyRoleArn reports whether the supplied RoleArn opts the
|
||||
// caller into claim-based policy mode. Either the empty string (caller
|
||||
// omitted RoleArn entirely; common for SDKs that didn't expect to need one)
|
||||
// or the explicit sentinel triggers the mode.
|
||||
func IsClaimBasedPolicyRoleArn(arn string) bool {
|
||||
return arn == "" || arn == ClaimBasedPolicyRoleArn
|
||||
}
|
||||
|
||||
// STSService provides Security Token Service functionality
|
||||
// This service is now completely stateless - all session information is embedded
|
||||
// in JWT tokens, eliminating the need for session storage and enabling true
|
||||
@@ -79,6 +95,31 @@ type STSService struct {
|
||||
issuerToProvider map[string]providers.IdentityProvider // Efficient issuer-based provider lookup
|
||||
tokenGenerator *TokenGenerator
|
||||
trustPolicyValidator TrustPolicyValidator // Interface for trust policy validation
|
||||
|
||||
// iamManagedOIDCMu guards iamManagedOIDCByIssuer. The map is the live view
|
||||
// of providers persisted in the IAM-managed OIDCProviderStore; it is
|
||||
// atomically replaced by SetIAMManagedOIDCProviders whenever the store
|
||||
// changes (either via a local IAM API call or a metadata-subscribe event
|
||||
// from a peer). Lookups consult this map first and fall back to the
|
||||
// static-config issuerToProvider so admin-managed entries always take
|
||||
// precedence over the bootstrap config.
|
||||
//
|
||||
// The slice value lets multiple records share an issuer when each is
|
||||
// scoped to a different account; lookup picks the entry whose AccountID
|
||||
// matches the role being assumed (or the global, AccountID="" entry as a
|
||||
// fallback). Without this, two accounts' records for the same issuer
|
||||
// would race for one map slot and a token could be validated by a
|
||||
// provider that wasn't scoped to the role's account.
|
||||
iamManagedOIDCMu sync.RWMutex
|
||||
iamManagedOIDCByIssuer map[string][]ScopedOIDCProvider
|
||||
}
|
||||
|
||||
// ScopedOIDCProvider pairs an OIDC IdentityProvider with the account it is
|
||||
// scoped to. AccountID="" means the provider is global (usable from any
|
||||
// account).
|
||||
type ScopedOIDCProvider struct {
|
||||
AccountID string
|
||||
Provider providers.IdentityProvider
|
||||
}
|
||||
|
||||
// GetTokenGenerator returns the token generator used by the STS service.
|
||||
@@ -254,6 +295,9 @@ type SessionInfo struct {
|
||||
|
||||
// Credentials are the temporary credentials for this session
|
||||
Credentials *Credentials `json:"credentials"`
|
||||
|
||||
// ParentUser is the stable hashed identity (sub+iss) derived at federation time.
|
||||
ParentUser string `json:"parentUser,omitempty"`
|
||||
}
|
||||
|
||||
// NewSTSService creates a new STS service
|
||||
@@ -421,6 +465,69 @@ func (s *STSService) GetProviders() map[string]providers.IdentityProvider {
|
||||
return s.providers
|
||||
}
|
||||
|
||||
// SetIAMManagedOIDCProviders atomically replaces the IAM-managed OIDC
|
||||
// provider map. Pass nil or an empty map to clear all managed entries. The
|
||||
// caller passes a fully-built map keyed by issuer URL; the slice value lets
|
||||
// per-account records coexist under the same issuer.
|
||||
func (s *STSService) SetIAMManagedOIDCProviders(byIssuer map[string][]ScopedOIDCProvider) {
|
||||
// Defensively copy so callers can keep mutating their map without affecting
|
||||
// in-flight lookups. A nil input becomes an empty map for cheap reads.
|
||||
cp := make(map[string][]ScopedOIDCProvider, len(byIssuer))
|
||||
for issuer, scoped := range byIssuer {
|
||||
if issuer == "" {
|
||||
continue
|
||||
}
|
||||
entries := make([]ScopedOIDCProvider, 0, len(scoped))
|
||||
for _, sp := range scoped {
|
||||
if sp.Provider == nil {
|
||||
continue
|
||||
}
|
||||
entries = append(entries, sp)
|
||||
}
|
||||
if len(entries) > 0 {
|
||||
cp[issuer] = entries
|
||||
}
|
||||
}
|
||||
s.iamManagedOIDCMu.Lock()
|
||||
s.iamManagedOIDCByIssuer = cp
|
||||
s.iamManagedOIDCMu.Unlock()
|
||||
}
|
||||
|
||||
// lookupOIDCProviderForAccount returns the provider that should validate
|
||||
// tokens from `issuer` when the caller is assuming a role in `accountID`.
|
||||
// Selection order:
|
||||
// 1. IAM-managed record exactly scoped to accountID (when accountID != "");
|
||||
// 2. IAM-managed record with empty AccountID (global);
|
||||
// 3. static-config issuerToProvider (legacy path; account-agnostic).
|
||||
//
|
||||
// Without the (issuer, account) key, two records for the same issuer (e.g.
|
||||
// account A with clientIDs=[a] and account B with clientIDs=[b]) would race
|
||||
// for one map slot, and a token destined for account B could be validated by
|
||||
// account A's record. The role-account check in
|
||||
// IAMManager.enforceProviderAccountScope blocks the cross-account assumption
|
||||
// itself, but the validation must use the right record's clientIDs and
|
||||
// thumbprints in the first place.
|
||||
func (s *STSService) lookupOIDCProviderForAccount(issuer, accountID string) (providers.IdentityProvider, bool) {
|
||||
s.iamManagedOIDCMu.RLock()
|
||||
scoped := s.iamManagedOIDCByIssuer[issuer]
|
||||
var globalMatch providers.IdentityProvider
|
||||
for _, sp := range scoped {
|
||||
if accountID != "" && sp.AccountID == accountID {
|
||||
s.iamManagedOIDCMu.RUnlock()
|
||||
return sp.Provider, true
|
||||
}
|
||||
if sp.AccountID == "" && globalMatch == nil {
|
||||
globalMatch = sp.Provider
|
||||
}
|
||||
}
|
||||
s.iamManagedOIDCMu.RUnlock()
|
||||
if globalMatch != nil {
|
||||
return globalMatch, true
|
||||
}
|
||||
p, ok := s.issuerToProvider[issuer]
|
||||
return p, ok
|
||||
}
|
||||
|
||||
// SetTrustPolicyValidator sets the trust policy validator for role assumption validation
|
||||
func (s *STSService) SetTrustPolicyValidator(validator TrustPolicyValidator) {
|
||||
s.trustPolicyValidator = validator
|
||||
@@ -451,23 +558,50 @@ func (s *STSService) AssumeRoleWithWebIdentity(ctx context.Context, request *Ass
|
||||
sessionPolicy = normalized
|
||||
}
|
||||
|
||||
// 1. Validate the web identity token with appropriate provider
|
||||
externalIdentity, provider, err := s.validateWebIdentityToken(ctx, request.WebIdentityToken)
|
||||
// 1. Validate the web identity token with appropriate provider. The role
|
||||
// ARN's account scopes which IAM-managed record may validate the token —
|
||||
// see lookupOIDCProviderForAccount. ParseRoleARN returns "" when the
|
||||
// caller passed a legacy or claim-based ARN, in which case lookup falls
|
||||
// back to a global (account-less) record only.
|
||||
roleAccountID := utils.ParseRoleARN(request.RoleArn).AccountID
|
||||
externalIdentity, provider, err := s.validateWebIdentityToken(ctx, request.WebIdentityToken, roleAccountID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to validate web identity token: %w", err)
|
||||
}
|
||||
|
||||
// 2. Check if the role exists and can be assumed (includes trust policy validation)
|
||||
if err := s.validateRoleAssumptionForWebIdentity(ctx, request.RoleArn, request.WebIdentityToken, request.DurationSeconds); err != nil {
|
||||
return nil, fmt.Errorf("role assumption denied: %w", err)
|
||||
// 2. Decide between concrete-role mode and claim-based policy mode.
|
||||
// Claim-based mode requires both the sentinel RoleArn and a non-empty
|
||||
// ClaimPolicies list — the second check guards against an IDP that just
|
||||
// happens not to emit the policy claim today.
|
||||
claimMode := IsClaimBasedPolicyRoleArn(request.RoleArn) && len(externalIdentity.ClaimPolicies) > 0
|
||||
effectiveRoleArn := request.RoleArn
|
||||
if claimMode {
|
||||
// Replace an empty RoleArn with the constant sentinel so the assumed-
|
||||
// role ARN GenerateAssumedRoleArn produces below carries a stable,
|
||||
// session-name-keyed principal that policy evaluation can log and
|
||||
// rate-limit on.
|
||||
effectiveRoleArn = ClaimBasedPolicyRoleArn
|
||||
} else if request.RoleArn == "" {
|
||||
return nil, fmt.Errorf("RoleArn is required when claim-based policy mode is not configured")
|
||||
} else if request.RoleArn == ClaimBasedPolicyRoleArn {
|
||||
return nil, fmt.Errorf("claim-based policy mode requires the IDP to emit policies via the configured policyClaim")
|
||||
}
|
||||
|
||||
// 3. Calculate session duration, capping at the source token's expiration
|
||||
// 3. Trust-policy validation only runs in concrete-role mode. In
|
||||
// claim-mode the IDP is the sole authority for both authentication and
|
||||
// authorization, so there is no role definition to consult.
|
||||
if !claimMode {
|
||||
if err := s.validateRoleAssumptionForWebIdentity(ctx, request.RoleArn, request.WebIdentityToken, request.DurationSeconds); err != nil {
|
||||
return nil, fmt.Errorf("role assumption denied: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Calculate session duration, capping at the source token's expiration
|
||||
// This ensures sessions from short-lived tokens (e.g., GitLab CI job tokens) don't outlive their source
|
||||
sessionDuration := s.calculateSessionDuration(request.DurationSeconds, externalIdentity.TokenExpiration)
|
||||
expiresAt := time.Now().Add(sessionDuration)
|
||||
|
||||
// 4. Generate session ID and credentials
|
||||
// 5. Generate session ID and credentials
|
||||
sessionId, err := GenerateSessionId()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate session ID: %w", err)
|
||||
@@ -479,10 +613,10 @@ func (s *STSService) AssumeRoleWithWebIdentity(ctx context.Context, request *Ass
|
||||
return nil, fmt.Errorf("failed to generate credentials: %w", err)
|
||||
}
|
||||
|
||||
// 5. Create comprehensive JWT session token with all session information embedded
|
||||
// 6. Create comprehensive JWT session token with all session information embedded
|
||||
assumedRoleUser := &AssumedRoleUser{
|
||||
AssumedRoleId: request.RoleArn,
|
||||
Arn: GenerateAssumedRoleArn(request.RoleArn, request.RoleSessionName),
|
||||
AssumedRoleId: effectiveRoleArn,
|
||||
Arn: GenerateAssumedRoleArn(effectiveRoleArn, request.RoleSessionName),
|
||||
Subject: externalIdentity.UserID,
|
||||
}
|
||||
|
||||
@@ -506,13 +640,38 @@ func (s *STSService) AssumeRoleWithWebIdentity(ctx context.Context, request *Ass
|
||||
// Add sub as well since it's commonly used
|
||||
requestContext["sub"] = externalIdentity.UserID
|
||||
|
||||
// Compute a stable parent-user hash from (sub, iss). Only this tuple is
|
||||
// guaranteed stable across token refresh per OIDC Core 1.0, so this is the
|
||||
// right key for any per-identity state (audit trail, future quotas).
|
||||
parentUser := ComputeParentUser(externalIdentity.UserID, externalIdentity.Issuer)
|
||||
if parentUser != "" {
|
||||
// Surface as aws:userid so policies can reference it directly without
|
||||
// caring about token-rotation churn.
|
||||
requestContext["aws:userid"] = parentUser
|
||||
}
|
||||
|
||||
// Surface principal session tags as aws:PrincipalTag/<key>. The OIDC
|
||||
// provider has already filtered the claim namespace through its
|
||||
// AllowedPrincipalTagKeys list (see filterPrincipalTags), so anything
|
||||
// reaching us here is on the operator's opt-in list. The full claim
|
||||
// is dropped if the allowlist is empty, which is the secure default.
|
||||
for k, v := range externalIdentity.PrincipalTags {
|
||||
requestContext["aws:PrincipalTag/"+k] = v
|
||||
}
|
||||
|
||||
// Create rich JWT claims with all session information
|
||||
sessionClaims := NewSTSSessionClaims(sessionId, s.Config.Issuer, expiresAt).
|
||||
WithSessionName(request.RoleSessionName).
|
||||
WithRoleInfo(request.RoleArn, assumedRoleUser.Arn, assumedRoleUser.Arn).
|
||||
WithIdentityProvider(provider.Name(), externalIdentity.UserID, "").
|
||||
WithRoleInfo(effectiveRoleArn, assumedRoleUser.Arn, assumedRoleUser.Arn).
|
||||
WithIdentityProvider(provider.Name(), externalIdentity.UserID, externalIdentity.Issuer).
|
||||
WithMaxDuration(sessionDuration).
|
||||
WithRequestContext(requestContext)
|
||||
if claimMode {
|
||||
sessionClaims.WithPolicies(externalIdentity.ClaimPolicies)
|
||||
}
|
||||
if parentUser != "" {
|
||||
sessionClaims.WithParentUser(parentUser)
|
||||
}
|
||||
if sessionPolicy != "" {
|
||||
sessionClaims.WithSessionPolicy(sessionPolicy)
|
||||
}
|
||||
@@ -661,12 +820,13 @@ func (s *STSService) ValidateSessionToken(ctx context.Context, sessionToken stri
|
||||
|
||||
// Helper methods for AssumeRoleWithWebIdentity
|
||||
|
||||
// validateAssumeRoleWithWebIdentityRequest validates the request parameters
|
||||
// validateAssumeRoleWithWebIdentityRequest validates the request parameters.
|
||||
//
|
||||
// RoleArn validation lives in AssumeRoleWithWebIdentity itself rather than
|
||||
// here: once we've parsed the JWT we know whether the caller has
|
||||
// ClaimPolicies and can decide between concrete-role mode and claim-mode,
|
||||
// which in turn determines whether an empty/sentinel RoleArn is acceptable.
|
||||
func (s *STSService) validateAssumeRoleWithWebIdentityRequest(request *AssumeRoleWithWebIdentityRequest) error {
|
||||
if request.RoleArn == "" {
|
||||
return fmt.Errorf("RoleArn is required")
|
||||
}
|
||||
|
||||
if request.WebIdentityToken == "" {
|
||||
return fmt.Errorf("WebIdentityToken is required")
|
||||
}
|
||||
@@ -688,7 +848,7 @@ func (s *STSService) validateAssumeRoleWithWebIdentityRequest(request *AssumeRol
|
||||
// validateWebIdentityToken validates the web identity token with strict issuer-to-provider mapping
|
||||
// SECURITY: JWT tokens with a specific issuer claim MUST only be validated by the provider for that issuer
|
||||
// SECURITY: This method only accepts JWT tokens. Non-JWT authentication must use AssumeRoleWithCredentials with explicit ProviderName.
|
||||
func (s *STSService) validateWebIdentityToken(ctx context.Context, token string) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
func (s *STSService) validateWebIdentityToken(ctx context.Context, token, roleAccountID string) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
// Try to extract issuer from JWT token for strict validation
|
||||
issuer, err := s.extractIssuerFromJWT(token)
|
||||
if err != nil {
|
||||
@@ -699,8 +859,12 @@ func (s *STSService) validateWebIdentityToken(ctx context.Context, token string)
|
||||
return nil, nil, fmt.Errorf("web identity token must be a valid JWT token: %w", err)
|
||||
}
|
||||
|
||||
// Look up the specific provider for this issuer
|
||||
provider, exists := s.issuerToProvider[issuer]
|
||||
// Look up the specific provider for this issuer, scoped to the role's
|
||||
// account when known. IAM-managed records (admin-controlled, mutable at
|
||||
// runtime) take precedence over the static-config map so an operator's
|
||||
// CreateOpenIDConnectProvider call can shadow a bootstrap entry without
|
||||
// requiring a restart.
|
||||
provider, exists := s.lookupOIDCProviderForAccount(issuer, roleAccountID)
|
||||
if !exists {
|
||||
// SECURITY: If no provider is registered for this issuer, fail immediately
|
||||
// This prevents JWT tokens from being validated by unintended providers
|
||||
@@ -735,9 +899,19 @@ func (s *STSService) validateWebIdentityToken(ctx context.Context, token string)
|
||||
}
|
||||
|
||||
// ValidateWebIdentityToken is a public method that exposes secure token validation for external use
|
||||
// This method uses issuer-based lookup to select the correct provider, ensuring security and efficiency
|
||||
// This method uses issuer-based lookup to select the correct provider, ensuring security and efficiency.
|
||||
// External callers without role context get the account-agnostic lookup (global IAM-managed records
|
||||
// only, then static-config); call ValidateWebIdentityTokenForAccount when the assumed-role account
|
||||
// is known.
|
||||
func (s *STSService) ValidateWebIdentityToken(ctx context.Context, token string) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
return s.validateWebIdentityToken(ctx, token)
|
||||
return s.validateWebIdentityToken(ctx, token, "")
|
||||
}
|
||||
|
||||
// ValidateWebIdentityTokenForAccount mirrors ValidateWebIdentityToken but
|
||||
// scopes the IAM-managed provider lookup to roleAccountID. Pass "" for
|
||||
// callers that don't yet know the account (e.g. claim-based mode).
|
||||
func (s *STSService) ValidateWebIdentityTokenForAccount(ctx context.Context, token, roleAccountID string) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
return s.validateWebIdentityToken(ctx, token, roleAccountID)
|
||||
}
|
||||
|
||||
// extractIssuerFromJWT extracts the issuer (iss) claim from a JWT token without verification
|
||||
|
||||
@@ -86,6 +86,24 @@ func (list *ChunkWrittenIntervalList) WrittenSize() (writtenByteCount int64) {
|
||||
return
|
||||
}
|
||||
|
||||
// IsContiguouslyWritten reports whether the written bytes form one
|
||||
// unbroken run starting at offset 0. Pressure-driven sealing uses this
|
||||
// to avoid racing in-flight FUSE writeback on a gap range — sealing a
|
||||
// gappy chunk would emit volume chunks with no coverage for the gap and
|
||||
// reads would silently zero-fill it (issue #9330).
|
||||
func (list *ChunkWrittenIntervalList) IsContiguouslyWritten() bool {
|
||||
first := list.head.next
|
||||
if first == list.tail || first.StartOffset != 0 {
|
||||
return false
|
||||
}
|
||||
for t := first; t.next != list.tail; t = t.next {
|
||||
if t.stopOffset != t.next.StartOffset {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (list *ChunkWrittenIntervalList) addInterval(interval *ChunkWrittenInterval) {
|
||||
|
||||
//t := list.head
|
||||
|
||||
@@ -81,6 +81,37 @@ func hasData(usage *ChunkWrittenIntervalList, chunkStartOffset, x int64) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func TestIsContiguouslyWritten(t *testing.T) {
|
||||
const chunkSize int64 = 2 * 1024 * 1024
|
||||
cases := []struct {
|
||||
name string
|
||||
writes [][2]int64
|
||||
expected bool
|
||||
}{
|
||||
{name: "empty", writes: nil, expected: false},
|
||||
{name: "single full", writes: [][2]int64{{0, chunkSize}}, expected: true},
|
||||
{name: "single partial at start", writes: [][2]int64{{0, chunkSize / 4}}, expected: true},
|
||||
{name: "two adjacent halves in order", writes: [][2]int64{{0, chunkSize / 2}, {chunkSize / 2, chunkSize}}, expected: true},
|
||||
{name: "two adjacent halves out of order", writes: [][2]int64{{chunkSize / 2, chunkSize}, {0, chunkSize / 2}}, expected: true},
|
||||
{name: "overlapping covers everything", writes: [][2]int64{{0, chunkSize*3/4 + 1}, {chunkSize / 2, chunkSize}}, expected: true},
|
||||
{name: "three adjacent thirds", writes: [][2]int64{{0, chunkSize / 3}, {chunkSize / 3, 2 * chunkSize / 3}, {2 * chunkSize / 3, chunkSize}}, expected: true},
|
||||
{name: "single partial in middle", writes: [][2]int64{{chunkSize / 4, chunkSize / 2}}, expected: false},
|
||||
{name: "first byte missing", writes: [][2]int64{{1, chunkSize}}, expected: false},
|
||||
{name: "gap in middle", writes: [][2]int64{{0, chunkSize / 4}, {chunkSize / 2, chunkSize}}, expected: false},
|
||||
{name: "two intervals with 1-byte gap", writes: [][2]int64{{0, 100}, {101, 200}}, expected: false},
|
||||
{name: "three intervals with middle gap", writes: [][2]int64{{0, chunkSize / 4}, {chunkSize / 3, chunkSize / 2}, {chunkSize / 2, chunkSize}}, expected: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
list := newChunkWrittenIntervalList()
|
||||
for i, w := range tc.writes {
|
||||
list.MarkWritten(w[0], w[1], int64(i+1))
|
||||
}
|
||||
assert.Equal(t, tc.expected, list.IsContiguouslyWritten(), "IsContiguouslyWritten mismatch")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsComplete_AdjacentIntervals(t *testing.T) {
|
||||
// Linux FUSE delivers writes up to FUSE_MAX_PAGES_PER_REQ
|
||||
// (typically 1 MiB) per op, so a 2 MiB chunk filled by sequential
|
||||
|
||||
@@ -11,6 +11,7 @@ type PageChunk interface {
|
||||
WriteDataAt(src []byte, offset int64, tsNs int64) (n int)
|
||||
ReadDataAt(p []byte, off int64, tsNs int64) (maxStop int64)
|
||||
IsComplete() bool
|
||||
IsContiguouslyWritten() bool
|
||||
ActivityScore() int64
|
||||
WrittenSize() int64
|
||||
LastWriteTsNs() int64
|
||||
|
||||
@@ -81,6 +81,13 @@ func (mc *MemChunk) IsComplete() bool {
|
||||
return mc.usage.IsComplete(mc.chunkSize)
|
||||
}
|
||||
|
||||
func (mc *MemChunk) IsContiguouslyWritten() bool {
|
||||
mc.RLock()
|
||||
defer mc.RUnlock()
|
||||
|
||||
return mc.usage.IsContiguouslyWritten()
|
||||
}
|
||||
|
||||
func (mc *MemChunk) ActivityScore() int64 {
|
||||
return mc.activityScore.ActivityScore()
|
||||
}
|
||||
|
||||
@@ -172,6 +172,12 @@ func (sc *SwapFileChunk) IsComplete() bool {
|
||||
return sc.usage.IsComplete(sc.swapfile.chunkSize)
|
||||
}
|
||||
|
||||
func (sc *SwapFileChunk) IsContiguouslyWritten() bool {
|
||||
sc.RLock()
|
||||
defer sc.RUnlock()
|
||||
return sc.usage.IsContiguouslyWritten()
|
||||
}
|
||||
|
||||
func (sc *SwapFileChunk) ActivityScore() int64 {
|
||||
return sc.activityScore.ActivityScore()
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package page_writer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
@@ -118,34 +119,23 @@ func (up *UploadPipeline) SaveDataAt(p []byte, off int64, isSequential bool, tsN
|
||||
}
|
||||
if !found {
|
||||
if len(up.writableChunks) > up.writableChunkLimit {
|
||||
// if current file chunks is over the per file buffer count limit
|
||||
// Per-pipeline soft cap. Seal the fullest gap-free chunk;
|
||||
// gappy chunks must wait so in-flight FUSE writeback can fill
|
||||
// the gap (issue #9330). If none qualifies, fall through —
|
||||
// the memChunkCounter ceiling below redirects to swap.
|
||||
candidateChunkIndex, fullness := LogicChunkIndex(-1), int64(0)
|
||||
for lci, mc := range up.writableChunks {
|
||||
chunkFullness := mc.WrittenSize()
|
||||
if fullness < chunkFullness {
|
||||
if !mc.IsContiguouslyWritten() {
|
||||
continue
|
||||
}
|
||||
if b := mc.WrittenSize(); b > fullness {
|
||||
candidateChunkIndex = lci
|
||||
fullness = chunkFullness
|
||||
fullness = b
|
||||
}
|
||||
}
|
||||
/* // this algo generates too many chunks
|
||||
candidateChunkIndex, lowestActivityScore := LogicChunkIndex(-1), int64(math.MaxInt64)
|
||||
for wci, wc := range up.writableChunks {
|
||||
activityScore := wc.ActivityScore()
|
||||
if lowestActivityScore >= activityScore {
|
||||
if lowestActivityScore == activityScore {
|
||||
chunkFullness := wc.WrittenSize()
|
||||
if fullness < chunkFullness {
|
||||
candidateChunkIndex = lci
|
||||
fullness = chunkFullness
|
||||
}
|
||||
}
|
||||
candidateChunkIndex = wci
|
||||
lowestActivityScore = activityScore
|
||||
}
|
||||
if candidateChunkIndex >= 0 {
|
||||
up.moveToSealed(up.writableChunks[candidateChunkIndex], candidateChunkIndex)
|
||||
}
|
||||
*/
|
||||
up.moveToSealed(up.writableChunks[candidateChunkIndex], candidateChunkIndex)
|
||||
// fmt.Printf("flush chunk %d with %d bytes written\n", logicChunkIndex, fullness)
|
||||
}
|
||||
// fmt.Printf("isSequential:%v len(up.writableChunks):%v memChunkCounter:%v", isSequential, len(up.writableChunks), memChunkCounter)
|
||||
if isSequential &&
|
||||
@@ -270,28 +260,52 @@ func (up *UploadPipeline) moveToSealed(memChunk PageChunk, logicChunkIndex Logic
|
||||
up.chunksLock.Lock()
|
||||
}
|
||||
|
||||
// EvictOneWritableChunk force-seals the fullest writable chunk in this
|
||||
// pipeline, submitting it for async upload. Called by the accountant's
|
||||
// evictor when Reserve would block. Returns true if a chunk was sealed.
|
||||
// The fullest-chunk heuristic matches the over-limit path in SaveDataAt:
|
||||
// sealing the chunk closest to full maximizes the upload's usefulness
|
||||
// and avoids thrashing on repeatedly re-creating the same half-empty
|
||||
// chunk. Callers must not hold up.chunksLock.
|
||||
// EvictOneWritableChunk force-seals one writable chunk so the accountant's
|
||||
// Reserve loop can make progress. Strict pass picks the fullest gap-free
|
||||
// chunk (issue #9330). Fallback picks the oldest non-empty writer when
|
||||
// nothing is gap-free; without it Reserve deadlocks (cond.Wait only wakes
|
||||
// on Release, Release only fires on upload completion). Callers must not
|
||||
// hold up.chunksLock.
|
||||
func (up *UploadPipeline) EvictOneWritableChunk() bool {
|
||||
up.chunksLock.Lock()
|
||||
defer up.chunksLock.Unlock()
|
||||
if len(up.writableChunks) == 0 {
|
||||
return false
|
||||
}
|
||||
var bestIndex LogicChunkIndex
|
||||
var bestBytes int64 = -1
|
||||
|
||||
bestIndex := LogicChunkIndex(-1)
|
||||
var bestBytes int64
|
||||
for lci, wc := range up.writableChunks {
|
||||
if !wc.IsContiguouslyWritten() {
|
||||
continue
|
||||
}
|
||||
if b := wc.WrittenSize(); b > bestBytes {
|
||||
bestIndex = lci
|
||||
bestBytes = b
|
||||
}
|
||||
}
|
||||
if bestBytes < 0 {
|
||||
|
||||
if bestIndex < 0 {
|
||||
oldestTsNs := int64(math.MaxInt64)
|
||||
var fallbackBytes int64
|
||||
for lci, wc := range up.writableChunks {
|
||||
b := wc.WrittenSize()
|
||||
if b == 0 {
|
||||
continue
|
||||
}
|
||||
ts := wc.LastWriteTsNs()
|
||||
if ts == 0 {
|
||||
continue
|
||||
}
|
||||
if ts < oldestTsNs || (ts == oldestTsNs && b > fallbackBytes) {
|
||||
bestIndex = lci
|
||||
oldestTsNs = ts
|
||||
fallbackBytes = b
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if bestIndex < 0 {
|
||||
return false
|
||||
}
|
||||
up.moveToSealed(up.writableChunks[bestIndex], bestIndex)
|
||||
@@ -330,6 +344,13 @@ func (up *UploadPipeline) ProactiveFlush(nowNs int64, idleThresholdNs int64, max
|
||||
if age < idleThresholdNs {
|
||||
continue
|
||||
}
|
||||
// Skip gappy chunks; FUSE writeback may still be in flight for the
|
||||
// hole and SaveContent would bake it into split volume chunks
|
||||
// (issue #9330). Failing here is just a missed flush — FlushAll
|
||||
// at close still seals everything.
|
||||
if !chunk.IsContiguouslyWritten() {
|
||||
continue
|
||||
}
|
||||
written := chunk.WrittenSize()
|
||||
nearlyFull := written >= fillRatio
|
||||
behindFrontier := isSeq && int64(lci) <= frontier-int64(frontierLag)
|
||||
|
||||
@@ -46,3 +46,215 @@ func confirmRange(t *testing.T, uploadPipeline *UploadPipeline, startOff, stopOf
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pressure-driven eviction must not seal a chunk with a leading or
|
||||
// internal gap (issue #9330).
|
||||
func TestEvictOneWritableChunk_SkipsGappyChunks(t *testing.T) {
|
||||
const cs int64 = 2 * 1024 * 1024
|
||||
// nil saveToStorage so the async upload SaveContent is a no-op.
|
||||
up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(2), cs, nil, 16, "", nil)
|
||||
|
||||
block := make([]byte, cs/4)
|
||||
|
||||
// chunk 0: internal gap; chunk 1: leading gap; chunk 2: contiguous from 0.
|
||||
if _, err := up.SaveDataAt(block, 0, true, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, 3*cs/4, true, 2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs+cs/4, true, 3); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs+cs/2, true, 4); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, 2*cs, true, 5); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, 2*cs+cs/4, true, 6); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !up.EvictOneWritableChunk() {
|
||||
t.Fatalf("EvictOneWritableChunk returned false; expected contiguous chunk 2 to be evictable")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(2)]; stillWritable {
|
||||
t.Errorf("chunk 2 should have moved to sealed")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(0)]; !stillWritable {
|
||||
t.Errorf("chunk 0 (internal gap) must remain writable")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(1)]; !stillWritable {
|
||||
t.Errorf("chunk 1 (leading gap) must remain writable")
|
||||
}
|
||||
|
||||
// Filling holes makes IsComplete true; maybeMoveToSealed auto-seals.
|
||||
if _, err := up.SaveDataAt(block, cs/4, true, 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs/2, true, 8); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs, true, 9); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs+3*cs/4, true, 10); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(0)]; stillWritable {
|
||||
t.Errorf("chunk 0 should have auto-sealed after gap was filled")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(1)]; stillWritable {
|
||||
t.Errorf("chunk 1 should have auto-sealed after leading range was filled")
|
||||
}
|
||||
}
|
||||
|
||||
// When every chunk is gappy, the fallback must still seal one so
|
||||
// accountant.Reserve can wake; oldest-LastWriteTsNs wins.
|
||||
func TestEvictOneWritableChunk_FallbackPicksOldestGappy(t *testing.T) {
|
||||
const cs int64 = 2 * 1024 * 1024
|
||||
up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(2), cs, nil, 16, "", nil)
|
||||
|
||||
block := make([]byte, cs/4)
|
||||
|
||||
// Strictly increasing tsNs so chunk 0 is oldest; equal WrittenSize.
|
||||
if _, err := up.SaveDataAt(block, 0, true, 100); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, 3*cs/4, true, 101); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs+cs/4, true, 200); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs+cs/2, true, 201); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, 2*cs, true, 300); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, 2*cs+3*cs/4, true, 301); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !up.EvictOneWritableChunk() {
|
||||
t.Fatalf("fallback must seal a gappy chunk to free a Reserve slot")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(0)]; stillWritable {
|
||||
t.Errorf("oldest gappy chunk (0) should have been picked by the fallback")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(1)]; !stillWritable {
|
||||
t.Errorf("chunk 1 should remain writable")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(2)]; !stillWritable {
|
||||
t.Errorf("chunk 2 should remain writable")
|
||||
}
|
||||
}
|
||||
|
||||
// Strict pass preempts the fallback even when a gappy chunk is older.
|
||||
func TestEvictOneWritableChunk_PrefersStrictOverFallback(t *testing.T) {
|
||||
const cs int64 = 2 * 1024 * 1024
|
||||
up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(2), cs, nil, 16, "", nil)
|
||||
|
||||
block := make([]byte, cs/4)
|
||||
|
||||
// chunk 0 (older, gappy), chunk 1 (newer, contiguous from 0).
|
||||
if _, err := up.SaveDataAt(block, 0, true, 100); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, 3*cs/4, true, 101); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs, true, 200); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs+cs/4, true, 201); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !up.EvictOneWritableChunk() {
|
||||
t.Fatalf("EvictOneWritableChunk returned false")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(1)]; stillWritable {
|
||||
t.Errorf("contiguous chunk 1 must be picked over older gappy chunk 0")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(0)]; !stillWritable {
|
||||
t.Errorf("gappy chunk 0 must remain writable")
|
||||
}
|
||||
}
|
||||
|
||||
// ProactiveFlush also skips gappy chunks (issue #9330). No liveness
|
||||
// fallback here — unlike EvictOneWritableChunk, returning false is just
|
||||
// a missed optimization.
|
||||
func TestProactiveFlush_SkipsGappyChunks(t *testing.T) {
|
||||
const cs int64 = 2 * 1024 * 1024
|
||||
up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(2), cs, nil, 16, "", nil)
|
||||
|
||||
block := make([]byte, cs/4)
|
||||
|
||||
// chunk 0: internal gap; chunk 1: leading gap; chunk 2: contiguous from 0.
|
||||
if _, err := up.SaveDataAt(block, 0, true, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, 3*cs/4, true, 2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs+cs/4, true, 3); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs+cs/2, true, 4); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, 2*cs, true, 5); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, 2*cs+cs/4, true, 6); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// nowNs >> chunk timestamps so age clears the idle/maxHold gates;
|
||||
// fillRatio < WrittenSize so nearlyFull is true. Leaves
|
||||
// IsContiguouslyWritten as the only differentiator.
|
||||
const (
|
||||
nowNs int64 = 1_000_000_000
|
||||
idleThresholdNs int64 = 100
|
||||
maxHoldNs int64 = 200
|
||||
fillRatio int64 = cs / 8
|
||||
)
|
||||
if !up.ProactiveFlush(nowNs, idleThresholdNs, maxHoldNs, fillRatio, 0, false) {
|
||||
t.Fatalf("ProactiveFlush returned false; expected contiguous chunk 2 to be sealed")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(2)]; stillWritable {
|
||||
t.Errorf("chunk 2 should have moved to sealed")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(0)]; !stillWritable {
|
||||
t.Errorf("chunk 0 (internal gap) must remain writable")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(1)]; !stillWritable {
|
||||
t.Errorf("chunk 1 (leading gap) must remain writable")
|
||||
}
|
||||
|
||||
if up.ProactiveFlush(nowNs, idleThresholdNs, maxHoldNs, fillRatio, 0, false) {
|
||||
t.Errorf("ProactiveFlush returned true with only gappy chunks left")
|
||||
}
|
||||
|
||||
if _, err := up.SaveDataAt(block, cs/4, true, 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs/2, true, 8); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs, true, 9); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt(block, cs+3*cs/4, true, 10); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(0)]; stillWritable {
|
||||
t.Errorf("chunk 0 should have auto-sealed after gap was filled")
|
||||
}
|
||||
if _, stillWritable := up.writableChunks[LogicChunkIndex(1)]; stillWritable {
|
||||
t.Errorf("chunk 1 should have auto-sealed after leading range was filled")
|
||||
}
|
||||
}
|
||||
@@ -247,6 +247,9 @@ message VolumeUnmountResponse {
|
||||
message VolumeDeleteRequest {
|
||||
uint32 volume_id = 1;
|
||||
bool only_empty = 2;
|
||||
// when true, do not remove the cloud-tier object backing the volume.
|
||||
// used for moves where another server is taking over the same .vif.
|
||||
bool keep_remote_data = 3;
|
||||
}
|
||||
message VolumeDeleteResponse {
|
||||
}
|
||||
|
||||
@@ -1322,11 +1322,14 @@ func (*VolumeUnmountResponse) Descriptor() ([]byte, []int) {
|
||||
}
|
||||
|
||||
type VolumeDeleteRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
OnlyEmpty bool `protobuf:"varint,2,opt,name=only_empty,json=onlyEmpty,proto3" json:"only_empty,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
OnlyEmpty bool `protobuf:"varint,2,opt,name=only_empty,json=onlyEmpty,proto3" json:"only_empty,omitempty"`
|
||||
// when true, do not remove the cloud-tier object backing the volume.
|
||||
// used for moves where another server is taking over the same .vif.
|
||||
KeepRemoteData bool `protobuf:"varint,3,opt,name=keep_remote_data,json=keepRemoteData,proto3" json:"keep_remote_data,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *VolumeDeleteRequest) Reset() {
|
||||
@@ -1373,6 +1376,13 @@ func (x *VolumeDeleteRequest) GetOnlyEmpty() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *VolumeDeleteRequest) GetKeepRemoteData() bool {
|
||||
if x != nil {
|
||||
return x.KeepRemoteData
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type VolumeDeleteResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
@@ -6824,11 +6834,12 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"\x13VolumeMountResponse\"3\n" +
|
||||
"\x14VolumeUnmountRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\"\x17\n" +
|
||||
"\x15VolumeUnmountResponse\"Q\n" +
|
||||
"\x15VolumeUnmountResponse\"{\n" +
|
||||
"\x13VolumeDeleteRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1d\n" +
|
||||
"\n" +
|
||||
"only_empty\x18\x02 \x01(\bR\tonlyEmpty\"\x16\n" +
|
||||
"only_empty\x18\x02 \x01(\bR\tonlyEmpty\x12(\n" +
|
||||
"\x10keep_remote_data\x18\x03 \x01(\bR\x0ekeepRemoteData\"\x16\n" +
|
||||
"\x14VolumeDeleteResponse\"R\n" +
|
||||
"\x19VolumeMarkReadonlyRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x18\n" +
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.1
|
||||
// - protoc v3.21.12
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v6.33.4
|
||||
// source: volume_server.proto
|
||||
|
||||
package volume_server_pb
|
||||
@@ -781,148 +781,148 @@ type VolumeServerServer interface {
|
||||
type UnimplementedVolumeServerServer struct{}
|
||||
|
||||
func (UnimplementedVolumeServerServer) BatchDelete(context.Context, *BatchDeleteRequest) (*BatchDeleteResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method BatchDelete not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method BatchDelete not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VacuumVolumeCheck(context.Context, *VacuumVolumeCheckRequest) (*VacuumVolumeCheckResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VacuumVolumeCheck not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VacuumVolumeCheck not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VacuumVolumeCompact(*VacuumVolumeCompactRequest, grpc.ServerStreamingServer[VacuumVolumeCompactResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VacuumVolumeCompact not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VacuumVolumeCompact not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VacuumVolumeCommit(context.Context, *VacuumVolumeCommitRequest) (*VacuumVolumeCommitResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VacuumVolumeCommit not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VacuumVolumeCommit not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VacuumVolumeCleanup(context.Context, *VacuumVolumeCleanupRequest) (*VacuumVolumeCleanupResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VacuumVolumeCleanup not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VacuumVolumeCleanup not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) DeleteCollection(context.Context, *DeleteCollectionRequest) (*DeleteCollectionResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method DeleteCollection not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method DeleteCollection not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) AllocateVolume(context.Context, *AllocateVolumeRequest) (*AllocateVolumeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method AllocateVolume not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method AllocateVolume not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeSyncStatus(context.Context, *VolumeSyncStatusRequest) (*VolumeSyncStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeSyncStatus not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeSyncStatus not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeIncrementalCopy(*VolumeIncrementalCopyRequest, grpc.ServerStreamingServer[VolumeIncrementalCopyResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VolumeIncrementalCopy not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VolumeIncrementalCopy not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeMount(context.Context, *VolumeMountRequest) (*VolumeMountResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeMount not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeMount not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeUnmount(context.Context, *VolumeUnmountRequest) (*VolumeUnmountResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeUnmount not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeUnmount not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeDelete(context.Context, *VolumeDeleteRequest) (*VolumeDeleteResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeDelete not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeDelete not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeMarkReadonly(context.Context, *VolumeMarkReadonlyRequest) (*VolumeMarkReadonlyResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeMarkReadonly not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeMarkReadonly not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeMarkWritable(context.Context, *VolumeMarkWritableRequest) (*VolumeMarkWritableResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeMarkWritable not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeMarkWritable not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeConfigure(context.Context, *VolumeConfigureRequest) (*VolumeConfigureResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeConfigure not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeConfigure not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeStatus(context.Context, *VolumeStatusRequest) (*VolumeStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeStatus not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeStatus not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) GetState(context.Context, *GetStateRequest) (*GetStateResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method GetState not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetState not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) SetState(context.Context, *SetStateRequest) (*SetStateResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method SetState not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method SetState not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeCopy(*VolumeCopyRequest, grpc.ServerStreamingServer[VolumeCopyResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VolumeCopy not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VolumeCopy not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ReadVolumeFileStatus(context.Context, *ReadVolumeFileStatusRequest) (*ReadVolumeFileStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ReadVolumeFileStatus not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ReadVolumeFileStatus not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) CopyFile(*CopyFileRequest, grpc.ServerStreamingServer[CopyFileResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method CopyFile not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method CopyFile not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ReceiveFile(grpc.ClientStreamingServer[ReceiveFileRequest, ReceiveFileResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method ReceiveFile not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method ReceiveFile not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ReadNeedleBlob(context.Context, *ReadNeedleBlobRequest) (*ReadNeedleBlobResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ReadNeedleBlob not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ReadNeedleBlob not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ReadNeedleMeta(context.Context, *ReadNeedleMetaRequest) (*ReadNeedleMetaResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ReadNeedleMeta not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ReadNeedleMeta not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) WriteNeedleBlob(context.Context, *WriteNeedleBlobRequest) (*WriteNeedleBlobResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method WriteNeedleBlob not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method WriteNeedleBlob not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ReadAllNeedles(*ReadAllNeedlesRequest, grpc.ServerStreamingServer[ReadAllNeedlesResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method ReadAllNeedles not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method ReadAllNeedles not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeTailSender(*VolumeTailSenderRequest, grpc.ServerStreamingServer[VolumeTailSenderResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VolumeTailSender not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VolumeTailSender not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeTailReceiver(context.Context, *VolumeTailReceiverRequest) (*VolumeTailReceiverResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeTailReceiver not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeTailReceiver not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsGenerate(context.Context, *VolumeEcShardsGenerateRequest) (*VolumeEcShardsGenerateResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsGenerate not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsGenerate not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsRebuild(context.Context, *VolumeEcShardsRebuildRequest) (*VolumeEcShardsRebuildResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsRebuild not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsRebuild not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsCopy(context.Context, *VolumeEcShardsCopyRequest) (*VolumeEcShardsCopyResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsCopy not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsCopy not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsDelete(context.Context, *VolumeEcShardsDeleteRequest) (*VolumeEcShardsDeleteResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsDelete not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsDelete not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsMount(context.Context, *VolumeEcShardsMountRequest) (*VolumeEcShardsMountResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsMount not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsMount not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsUnmount(context.Context, *VolumeEcShardsUnmountRequest) (*VolumeEcShardsUnmountResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsUnmount not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsUnmount not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardRead(*VolumeEcShardReadRequest, grpc.ServerStreamingServer[VolumeEcShardReadResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VolumeEcShardRead not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VolumeEcShardRead not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcBlobDelete(context.Context, *VolumeEcBlobDeleteRequest) (*VolumeEcBlobDeleteResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcBlobDelete not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcBlobDelete not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsToVolume(context.Context, *VolumeEcShardsToVolumeRequest) (*VolumeEcShardsToVolumeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsToVolume not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsToVolume not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsInfo(context.Context, *VolumeEcShardsInfoRequest) (*VolumeEcShardsInfoResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsInfo not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsInfo not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeTierMoveDatToRemote(*VolumeTierMoveDatToRemoteRequest, grpc.ServerStreamingServer[VolumeTierMoveDatToRemoteResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VolumeTierMoveDatToRemote not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VolumeTierMoveDatToRemote not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeTierMoveDatFromRemote(*VolumeTierMoveDatFromRemoteRequest, grpc.ServerStreamingServer[VolumeTierMoveDatFromRemoteResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VolumeTierMoveDatFromRemote not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VolumeTierMoveDatFromRemote not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeServerStatus(context.Context, *VolumeServerStatusRequest) (*VolumeServerStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeServerStatus not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeServerStatus not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeServerLeave(context.Context, *VolumeServerLeaveRequest) (*VolumeServerLeaveResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeServerLeave not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeServerLeave not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) FetchAndWriteNeedle(context.Context, *FetchAndWriteNeedleRequest) (*FetchAndWriteNeedleResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method FetchAndWriteNeedle not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method FetchAndWriteNeedle not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ScrubVolume(context.Context, *ScrubVolumeRequest) (*ScrubVolumeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ScrubVolume not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ScrubVolume not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ScrubEcVolume(context.Context, *ScrubEcVolumeRequest) (*ScrubEcVolumeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ScrubEcVolume not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ScrubEcVolume not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) Query(*QueryRequest, grpc.ServerStreamingServer[QueriedStripe]) error {
|
||||
return status.Error(codes.Unimplemented, "method Query not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method Query not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeNeedleStatus(context.Context, *VolumeNeedleStatusRequest) (*VolumeNeedleStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeNeedleStatus not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeNeedleStatus not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) Ping(context.Context, *PingRequest) (*PingResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method Ping not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Ping not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) mustEmbedUnimplementedVolumeServerServer() {}
|
||||
func (UnimplementedVolumeServerServer) testEmbeddedByValue() {}
|
||||
@@ -935,7 +935,7 @@ type UnsafeVolumeServerServer interface {
|
||||
}
|
||||
|
||||
func RegisterVolumeServerServer(s grpc.ServiceRegistrar, srv VolumeServerServer) {
|
||||
// If the following call panics, it indicates UnimplementedVolumeServerServer was
|
||||
// If the following call pancis, it indicates UnimplementedVolumeServerServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
|
||||
@@ -153,6 +153,7 @@ func buildVolumeMetrics(
|
||||
ReplicaCount: 1,
|
||||
ExpectedReplicas: int(volume.ReplicaPlacement),
|
||||
IsReadOnly: volume.ReadOnly,
|
||||
HasRemoteCopy: volume.RemoteStorageName != "",
|
||||
}
|
||||
if metric.Size > 0 {
|
||||
metric.GarbageRatio = float64(metric.DeletedBytes) / float64(metric.Size)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -12,6 +13,8 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
const oidcProvidersDir = filer.IamConfigDirectory + "/oidc-providers"
|
||||
|
||||
func (s3a *S3ApiServer) subscribeMetaEvents(clientName string, lastTsNs int64, prefix string, directoriesToWatch []string) {
|
||||
|
||||
processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
@@ -30,12 +33,14 @@ func (s3a *S3ApiServer) subscribeMetaEvents(clientName string, lastTsNs int64, p
|
||||
// These handlers check for nil entries internally
|
||||
_ = s3a.onBucketMetadataChange(dir, message.OldEntry, message.NewEntry)
|
||||
_ = s3a.onIamConfigChange(dir, message.OldEntry, message.NewEntry)
|
||||
_ = s3a.onOIDCProviderChange(dir, message.OldEntry, message.NewEntry)
|
||||
_ = s3a.onCircuitBreakerConfigChange(dir, message.OldEntry, message.NewEntry)
|
||||
|
||||
// For moves across directories, replay a delete event for the source directory
|
||||
if message.NewParentPath != "" && resp.Directory != message.NewParentPath {
|
||||
_ = s3a.onBucketMetadataChange(resp.Directory, message.OldEntry, nil)
|
||||
_ = s3a.onIamConfigChange(resp.Directory, message.OldEntry, nil)
|
||||
_ = s3a.onOIDCProviderChange(resp.Directory, message.OldEntry, nil)
|
||||
_ = s3a.onCircuitBreakerConfigChange(resp.Directory, message.OldEntry, nil)
|
||||
}
|
||||
|
||||
@@ -123,6 +128,33 @@ func (s3a *S3ApiServer) onIamConfigChange(dir string, oldEntry *filer_pb.Entry,
|
||||
return nil
|
||||
}
|
||||
|
||||
// onOIDCProviderChange refreshes the IAM-managed OIDC provider runtime view
|
||||
// whenever the persisted store under /etc/iam/oidc-providers changes — both
|
||||
// for mutations originated on this S3 server (the local IAM API also calls
|
||||
// RefreshOIDCProvidersFromStore inline, but the subscribe path costs nothing
|
||||
// extra) and for mutations originated on peer S3 servers, which this is the
|
||||
// only mechanism to learn about. A single refresh covers create, update,
|
||||
// delete, and rename because the store is small and a full reload is the
|
||||
// safest way to reach a consistent view.
|
||||
func (s3a *S3ApiServer) onOIDCProviderChange(dir string, oldEntry *filer_pb.Entry, newEntry *filer_pb.Entry) error {
|
||||
if dir != oidcProvidersDir && !strings.HasPrefix(dir, oidcProvidersDir+"/") {
|
||||
return nil
|
||||
}
|
||||
if s3a.iam == nil || s3a.iam.iamIntegration == nil {
|
||||
return nil
|
||||
}
|
||||
s3iam, ok := s3a.iam.iamIntegration.(*S3IAMIntegration)
|
||||
if !ok || s3iam.iamManager == nil {
|
||||
return nil
|
||||
}
|
||||
if err := s3iam.iamManager.RefreshOIDCProvidersFromStore(context.Background()); err != nil {
|
||||
glog.Warningf("OIDC provider refresh after %s change failed: %v", dir, err)
|
||||
return err
|
||||
}
|
||||
glog.V(2).Infof("Refreshed IAM-managed OIDC providers after %s change", dir)
|
||||
return nil
|
||||
}
|
||||
|
||||
// onCircuitBreakerConfigChange handles circuit breaker config file changes (create, update, delete)
|
||||
func (s3a *S3ApiServer) onCircuitBreakerConfigChange(dir string, oldEntry *filer_pb.Entry, newEntry *filer_pb.Entry) error {
|
||||
if dir != s3_constants.CircuitBreakerConfigDir {
|
||||
|
||||
+42
-10
@@ -38,6 +38,7 @@ type SSEKMSKey struct {
|
||||
BucketKeyEnabled bool // Whether S3 Bucket Keys are enabled
|
||||
IV []byte // The initialization vector for encryption
|
||||
ChunkOffset int64 // Offset of this chunk within the original part (for IV calculation)
|
||||
KeyCommitment []byte // HMAC-SHA256 commitment binding key to IV+algorithm
|
||||
}
|
||||
|
||||
// SSEKMSMetadata represents the metadata stored with SSE-KMS objects
|
||||
@@ -49,6 +50,7 @@ type SSEKMSMetadata struct {
|
||||
BucketKeyEnabled bool `json:"bucketKeyEnabled"` // S3 Bucket Key optimization
|
||||
IV string `json:"iv"` // Base64-encoded initialization vector
|
||||
PartOffset int64 `json:"partOffset"` // Offset within original multipart part (for IV calculation)
|
||||
KeyCommitment string `json:"keyCommitment,omitempty"` // Base64-encoded HMAC key commitment
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -93,16 +95,15 @@ func CreateSSEKMSEncryptedReaderWithBucketKey(r io.Reader, keyID string, encrypt
|
||||
// Create CTR mode cipher stream
|
||||
stream := cipher.NewCTR(dataKeyResult.Block, iv)
|
||||
|
||||
// Create the SSE-KMS metadata using utility function
|
||||
// Create the SSE-KMS metadata using utility function. createSSEKMSKey
|
||||
// computes the key commitment too, so all encryption paths produce
|
||||
// commitment-bound metadata uniformly.
|
||||
sseKey := createSSEKMSKey(dataKeyResult, encryptionContext, bucketKeyEnabled, iv, 0)
|
||||
|
||||
// The IV is stored in SSE key metadata, so the encrypted stream does not need to prepend the IV
|
||||
// This ensures correct Content-Length for clients
|
||||
encryptedReader := &cipher.StreamReader{S: stream, R: r}
|
||||
|
||||
// Store IV in the SSE key for metadata storage
|
||||
sseKey.IV = iv
|
||||
|
||||
return encryptedReader, sseKey, nil
|
||||
}
|
||||
|
||||
@@ -122,15 +123,20 @@ func CreateSSEKMSEncryptedReaderWithBaseIVAndOffset(r io.Reader, keyID string, e
|
||||
// Ensure we clear the plaintext data key from memory when done
|
||||
defer clearKMSDataKey(dataKeyResult)
|
||||
|
||||
// Calculate unique IV using base IV and offset to prevent IV reuse in multipart uploads
|
||||
// Skip is not used here because we're encrypting from the start (not reading a range)
|
||||
// Calculate unique IV using base IV and offset to prevent IV reuse in multipart uploads.
|
||||
// Skip is not used here because we're encrypting from the start (not reading a range).
|
||||
iv, _ := calculateIVWithOffset(baseIV, offset)
|
||||
|
||||
// Create CTR mode cipher stream
|
||||
stream := cipher.NewCTR(dataKeyResult.Block, iv)
|
||||
|
||||
// Create the SSE-KMS metadata using utility function
|
||||
sseKey := createSSEKMSKey(dataKeyResult, encryptionContext, bucketKeyEnabled, iv, offset)
|
||||
// Store the BASE IV (not the offset-derived IV) in metadata. The decrypt
|
||||
// path applies calculateIVWithOffset to sseKey.IV when ChunkOffset > 0;
|
||||
// storing the derived IV here would cause it to offset twice and produce
|
||||
// the wrong CTR keystream. The key commitment, computed inside
|
||||
// createSSEKMSKey, therefore binds the base IV — exactly the value the
|
||||
// verify call at decrypt time hashes.
|
||||
sseKey := createSSEKMSKey(dataKeyResult, encryptionContext, bucketKeyEnabled, baseIV, offset)
|
||||
|
||||
// The IV is stored in SSE key metadata, so the encrypted stream does not need to prepend the IV
|
||||
// This ensures correct Content-Length for clients
|
||||
@@ -274,13 +280,19 @@ func (s3a *S3ApiServer) CreateSSEKMSEncryptedReaderForBucket(r io.Reader, bucket
|
||||
// Create CTR mode cipher stream
|
||||
stream := cipher.NewCTR(block, iv)
|
||||
|
||||
// Create the encrypting reader
|
||||
// Create the encrypting reader. Compute the HMAC commitment alongside
|
||||
// every other field so this bucket-scoped path is on the same downgrade-
|
||||
// resistant footing as the helper-driven paths above. Store the KMS
|
||||
// response's KeyID rather than the request's; CreateSSEKMSDecryptedReader
|
||||
// compares against decryptResp.KeyID, and a request alias would mismatch
|
||||
// the resolved ARN the response carries.
|
||||
sseKey := &SSEKMSKey{
|
||||
KeyID: keyID,
|
||||
KeyID: dataKeyResp.KeyID,
|
||||
EncryptedDataKey: dataKeyResp.CiphertextBlob,
|
||||
EncryptionContext: encryptionContext,
|
||||
BucketKeyEnabled: bucketKeyEnabled,
|
||||
IV: iv,
|
||||
KeyCommitment: ComputeKeyCommitment(dataKeyResp.Plaintext, iv, s3_constants.SSEAlgorithmKMS),
|
||||
}
|
||||
|
||||
return &cipher.StreamReader{S: stream, R: r}, sseKey, nil
|
||||
@@ -374,6 +386,11 @@ func CreateSSEKMSDecryptedReader(r io.Reader, sseKey *SSEKMSKey) (io.Reader, err
|
||||
return nil, fmt.Errorf("KMS key ID mismatch: expected %s, got %s", sseKey.KeyID, decryptResp.KeyID)
|
||||
}
|
||||
|
||||
// Verify key commitment before decryption if one exists in metadata
|
||||
if err := VerifyKeyCommitment(decryptResp.Plaintext, sseKey.IV, s3_constants.SSEAlgorithmKMS, sseKey.KeyCommitment); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Use the IV from the SSE key metadata, calculating offset if this is a chunked part
|
||||
if err := ValidateIV(sseKey.IV, "SSE key IV"); err != nil {
|
||||
return nil, fmt.Errorf("invalid IV in SSE key: %w", err)
|
||||
@@ -465,6 +482,11 @@ func SerializeSSEKMSMetadata(sseKey *SSEKMSKey) ([]byte, error) {
|
||||
PartOffset: sseKey.ChunkOffset, // Store within-part offset
|
||||
}
|
||||
|
||||
// Include key commitment if present
|
||||
if len(sseKey.KeyCommitment) > 0 {
|
||||
metadata.KeyCommitment = base64.StdEncoding.EncodeToString(sseKey.KeyCommitment)
|
||||
}
|
||||
|
||||
data, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal SSE-KMS metadata: %w", err)
|
||||
@@ -510,6 +532,15 @@ func DeserializeSSEKMSMetadata(data []byte) (*SSEKMSKey, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Decode key commitment if present
|
||||
var keyCommitment []byte
|
||||
if metadata.KeyCommitment != "" {
|
||||
keyCommitment, err = base64.StdEncoding.DecodeString(metadata.KeyCommitment)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode key commitment: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
sseKey := &SSEKMSKey{
|
||||
KeyID: metadata.KeyID,
|
||||
EncryptedDataKey: encryptedDataKey,
|
||||
@@ -517,6 +548,7 @@ func DeserializeSSEKMSMetadata(data []byte) (*SSEKMSKey, error) {
|
||||
BucketKeyEnabled: metadata.BucketKeyEnabled,
|
||||
IV: iv, // Restore IV for decryption
|
||||
ChunkOffset: metadata.PartOffset, // Use stored within-part offset
|
||||
KeyCommitment: keyCommitment,
|
||||
}
|
||||
|
||||
glog.V(4).Infof("Deserialized SSE-KMS metadata: keyID=%s, bucketKey=%t", sseKey.KeyID, sseKey.BucketKeyEnabled)
|
||||
|
||||
@@ -86,7 +86,12 @@ func clearKMSDataKey(result *KMSDataKeyResult) {
|
||||
}
|
||||
}
|
||||
|
||||
// createSSEKMSKey creates an SSEKMSKey struct from data key result and parameters
|
||||
// createSSEKMSKey creates an SSEKMSKey struct from data key result and parameters.
|
||||
// The HMAC key commitment is computed here (rather than at each call site) so
|
||||
// every SSE-KMS encryption path produces metadata that can later be verified
|
||||
// against tampering — a missing commitment was an attacker-controlled silent
|
||||
// downgrade vector. plaintext must still be live; deferred clearKMSDataKey
|
||||
// runs after this function returns.
|
||||
func createSSEKMSKey(result *KMSDataKeyResult, encryptionContext map[string]string, bucketKeyEnabled bool, iv []byte, chunkOffset int64) *SSEKMSKey {
|
||||
return &SSEKMSKey{
|
||||
KeyID: result.Response.KeyID,
|
||||
@@ -95,5 +100,6 @@ func createSSEKMSKey(result *KMSDataKeyResult, encryptionContext map[string]stri
|
||||
BucketKeyEnabled: bucketKeyEnabled,
|
||||
IV: iv,
|
||||
ChunkOffset: chunkOffset,
|
||||
KeyCommitment: ComputeKeyCommitment(result.Response.Plaintext, iv, s3_constants.SSEAlgorithmKMS),
|
||||
}
|
||||
}
|
||||
+309
-20
@@ -15,6 +15,8 @@ import (
|
||||
"io"
|
||||
mathrand "math/rand"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -36,10 +38,11 @@ const (
|
||||
|
||||
// SSES3Key represents a server-managed encryption key for SSE-S3
|
||||
type SSES3Key struct {
|
||||
Key []byte
|
||||
KeyID string
|
||||
Algorithm string
|
||||
IV []byte // Initialization Vector for this key
|
||||
Key []byte
|
||||
KeyID string
|
||||
Algorithm string
|
||||
IV []byte // Initialization Vector for this key
|
||||
KeyCommitment []byte // HMAC-SHA256 commitment binding key to IV+algorithm
|
||||
}
|
||||
|
||||
// IsSSES3RequestInternal checks if the request specifies SSE-S3 encryption
|
||||
@@ -116,6 +119,18 @@ func CreateSSES3EncryptedReader(reader io.Reader, key *SSES3Key) (io.Reader, []b
|
||||
|
||||
// CreateSSES3DecryptedReader creates a decrypted reader for SSE-S3 using IV from metadata
|
||||
func CreateSSES3DecryptedReader(reader io.Reader, key *SSES3Key, iv []byte) (io.Reader, error) {
|
||||
// IV comes from object metadata, which is mutable. Validate before passing
|
||||
// to cipher.NewCTR so a tampered length produces an error rather than the
|
||||
// crypto/cipher panic the documentation specifies.
|
||||
if err := ValidateIV(iv, "SSE-S3 IV"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Verify key commitment before decryption if one exists in metadata
|
||||
if err := VerifyKeyCommitment(key.Key, iv, key.Algorithm, key.KeyCommitment); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create AES cipher
|
||||
block, err := aes.NewCipher(key.Key)
|
||||
if err != nil {
|
||||
@@ -160,6 +175,9 @@ func SerializeSSES3Metadata(key *SSES3Key) ([]byte, error) {
|
||||
// Include IV if present (needed for chunk-level decryption)
|
||||
if key.IV != nil {
|
||||
metadata["iv"] = base64.StdEncoding.EncodeToString(key.IV)
|
||||
// Compute and store key commitment binding key ↔ IV + algorithm
|
||||
commitment := ComputeKeyCommitment(key.Key, key.IV, key.Algorithm)
|
||||
metadata["keyCommitment"] = base64.StdEncoding.EncodeToString(commitment)
|
||||
}
|
||||
|
||||
// Use JSON for proper serialization
|
||||
@@ -238,21 +256,40 @@ func DeserializeSSES3Metadata(data []byte, keyManager *SSES3KeyManager) (*SSES3K
|
||||
key.IV = iv
|
||||
}
|
||||
|
||||
// Restore key commitment if present (for tamper detection)
|
||||
if commitStr, exists := metadata["keyCommitment"]; exists {
|
||||
commitment, err := base64.StdEncoding.DecodeString(commitStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode key commitment: %w", err)
|
||||
}
|
||||
key.KeyCommitment = commitment
|
||||
}
|
||||
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// SSES3KeyManager manages SSE-S3 encryption keys using envelope encryption
|
||||
// Instead of storing keys in memory, it uses a super key (KEK) to encrypt/decrypt DEKs
|
||||
type SSES3KeyManager struct {
|
||||
mu sync.RWMutex
|
||||
superKey []byte // 256-bit master key (KEK - Key Encryption Key)
|
||||
filerClient filer_pb.FilerClient // Filer client for KEK persistence
|
||||
kekPath string // Path in filer where KEK is stored (e.g., /etc/s3/sse_kek)
|
||||
mu sync.RWMutex
|
||||
superKey []byte // 256-bit master key (KEK - Key Encryption Key)
|
||||
filerClient filer_pb.FilerClient // Filer client for KEK persistence
|
||||
kekPath string // Path in filer where KEK is stored (e.g., /etc/s3/sse_kek)
|
||||
kekPassphrase string // If set, KEK is encrypted at rest using a key derived from this passphrase
|
||||
}
|
||||
|
||||
const (
|
||||
// KEK storage layout on the filer. The migration code paths
|
||||
// updateKEKContent / generateAndSaveSuperKeyToFiler rely on the directory
|
||||
// + filename split; defaultKEKPath is the joined form kept for the
|
||||
// existing reader code.
|
||||
SSES3KEKDirectory = "/etc/s3"
|
||||
SSES3KEKParentDir = "/etc"
|
||||
SSES3KEKDirName = "s3"
|
||||
SSES3KEKFileName = "sse_kek"
|
||||
|
||||
// Legacy KEK path on the filer (backward compatibility)
|
||||
defaultKEKPath = "/etc/s3/sse_kek"
|
||||
defaultKEKPath = SSES3KEKDirectory + "/" + SSES3KEKFileName
|
||||
|
||||
// security.toml keys (also settable via env vars WEED_S3_SSE_KEK / WEED_S3_SSE_KEY):
|
||||
//
|
||||
@@ -263,16 +300,139 @@ const (
|
||||
// s3.sse.key: any secret string; a 256-bit key is derived via HKDF-SHA256.
|
||||
// Cannot be used while /etc/s3/sse_kek exists — the filer file must be
|
||||
// deleted first (to avoid silently orphaning old data).
|
||||
sseS3KEKConfigKey = "s3.sse.kek"
|
||||
sseS3KeyConfigKey = "s3.sse.key"
|
||||
sseS3KEKConfigKey = "s3.sse.kek"
|
||||
sseS3KeyConfigKey = "s3.sse.key"
|
||||
sseS3KEKPassphraseConfigKey = "s3.sse.kek.passphrase"
|
||||
)
|
||||
|
||||
// NewSSES3KeyManager creates a new SSE-S3 key manager with envelope encryption
|
||||
func NewSSES3KeyManager() *SSES3KeyManager {
|
||||
// This will be initialized properly when attached to an S3ApiServer
|
||||
return &SSES3KeyManager{
|
||||
// legacyKEKWrappingSalt is the fixed salt the original implementation used
|
||||
// for HKDF derivation. It is retained for backward compatibility — KEKs
|
||||
// wrapped before per-installation salts shipped (the v1 format below) are
|
||||
// still unwrappable. New writes always use a random salt.
|
||||
var legacyKEKWrappingSalt = []byte("seaweedfs-sse-s3-kek-wrapping-v1")
|
||||
|
||||
// kekWrappedV2Magic identifies the new on-disk format that prefixes the
|
||||
// wrapped KEK with a random salt. Seeing this magic at byte 0 of the
|
||||
// decoded payload tells unwrapKEK to read the per-installation salt
|
||||
// instead of falling back to legacyKEKWrappingSalt.
|
||||
var kekWrappedV2Magic = []byte{0x53, 0x57, 0x76, 0x32} // "SWv2"
|
||||
|
||||
// kekRandomSaltSize is the per-installation salt length in bytes for HKDF.
|
||||
// 32 bytes matches the SHA-256 output and is the standard recommendation.
|
||||
const kekRandomSaltSize = 32
|
||||
|
||||
|
||||
// NewSSES3KeyManager creates a new SSE-S3 key manager with envelope encryption.
|
||||
// If kekPassphrase is non-empty, the KEK is encrypted at rest using a key derived from it.
|
||||
func NewSSES3KeyManager(kekPassphrase ...string) *SSES3KeyManager {
|
||||
km := &SSES3KeyManager{
|
||||
kekPath: defaultKEKPath,
|
||||
}
|
||||
if len(kekPassphrase) > 0 {
|
||||
km.kekPassphrase = kekPassphrase[0]
|
||||
}
|
||||
return km
|
||||
}
|
||||
|
||||
// deriveWrappingKey derives a 256-bit AES key from the configured passphrase
|
||||
// using HKDF-SHA256 with the supplied salt. Per-installation random salts
|
||||
// land in the v2 format; the legacy fixed salt is still accepted for KEKs
|
||||
// that were wrapped before random salts shipped.
|
||||
func (km *SSES3KeyManager) deriveWrappingKey(salt []byte) ([]byte, error) {
|
||||
if km.kekPassphrase == "" {
|
||||
return nil, fmt.Errorf("no KEK passphrase configured")
|
||||
}
|
||||
hkdfReader := hkdf.New(sha256.New, []byte(km.kekPassphrase), salt, []byte("kek-wrapping"))
|
||||
wrappingKey := make([]byte, SSES3KeySize)
|
||||
if _, err := io.ReadFull(hkdfReader, wrappingKey); err != nil {
|
||||
return nil, fmt.Errorf("HKDF derive wrapping key: %w", err)
|
||||
}
|
||||
return wrappingKey, nil
|
||||
}
|
||||
|
||||
// wrapKEK encrypts the KEK using AES-GCM with a freshly-derived wrapping
|
||||
// key. Output is base64(magic || salt || nonce || ciphertext+tag) — the
|
||||
// random salt is the defence against rainbow-table precomputation against a
|
||||
// shared passphrase, and storing it next to the ciphertext means the
|
||||
// installation can rotate the passphrase without having to migrate the salt
|
||||
// separately.
|
||||
func (km *SSES3KeyManager) wrapKEK(kek []byte) ([]byte, error) {
|
||||
salt := make([]byte, kekRandomSaltSize)
|
||||
if _, err := io.ReadFull(rand.Reader, salt); err != nil {
|
||||
return nil, fmt.Errorf("generate KEK salt: %w", err)
|
||||
}
|
||||
wrappingKey, err := km.deriveWrappingKey(salt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
block, err := aes.NewCipher(wrappingKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
header := make([]byte, 0, len(kekWrappedV2Magic)+len(salt))
|
||||
header = append(header, kekWrappedV2Magic...)
|
||||
header = append(header, salt...)
|
||||
sealed := gcm.Seal(append(header, nonce...), nonce, kek, nil) // magic || salt || nonce || ciphertext+tag
|
||||
return []byte(base64.StdEncoding.EncodeToString(sealed)), nil
|
||||
}
|
||||
|
||||
// unwrapKEK decrypts a wrapped KEK produced by wrapKEK. Two on-disk formats
|
||||
// are accepted:
|
||||
//
|
||||
// v2 (preferred): magic("SWv2") || salt || nonce || ciphertext+tag — the
|
||||
// salt is read from the payload before HKDF runs.
|
||||
// v1 (legacy): nonce || ciphertext+tag — falls back to the fixed
|
||||
// legacyKEKWrappingSalt; rewrapping into v2 happens via the migration
|
||||
// path in loadSuperKeyFromFiler.
|
||||
//
|
||||
// The returned `isV2` flag tells the caller which format was on disk, so
|
||||
// the migration path can rewrap legacy entries without re-decoding the
|
||||
// base64 payload a second time.
|
||||
func (km *SSES3KeyManager) unwrapKEK(wrapped []byte) (kek []byte, isV2 bool, err error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(string(wrapped))
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("base64 decode wrapped KEK: %w", err)
|
||||
}
|
||||
|
||||
salt := legacyKEKWrappingSalt
|
||||
payload := raw
|
||||
if len(raw) > len(kekWrappedV2Magic)+kekRandomSaltSize && bytes.Equal(raw[:len(kekWrappedV2Magic)], kekWrappedV2Magic) {
|
||||
salt = raw[len(kekWrappedV2Magic) : len(kekWrappedV2Magic)+kekRandomSaltSize]
|
||||
payload = raw[len(kekWrappedV2Magic)+kekRandomSaltSize:]
|
||||
isV2 = true
|
||||
}
|
||||
|
||||
wrappingKey, err := km.deriveWrappingKey(salt)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
block, err := aes.NewCipher(wrappingKey)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if len(payload) < gcm.NonceSize() {
|
||||
return nil, false, fmt.Errorf("wrapped KEK too short")
|
||||
}
|
||||
nonce := payload[:gcm.NonceSize()]
|
||||
ciphertext := payload[gcm.NonceSize():]
|
||||
out, err := gcm.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return out, isV2, nil
|
||||
}
|
||||
|
||||
// deriveKeyFromSecret derives a 256-bit key from an arbitrary secret string
|
||||
@@ -433,10 +593,54 @@ func (km *SSES3KeyManager) loadSuperKeyFromFiler() error {
|
||||
return fmt.Errorf("KEK entry is empty")
|
||||
}
|
||||
|
||||
// Decode hex-encoded key
|
||||
key, err := hex.DecodeString(string(entry.Content))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode KEK: %w", err)
|
||||
var key []byte
|
||||
if km.kekPassphrase != "" {
|
||||
// Try to unwrap encrypted KEK first
|
||||
var wasV2 bool
|
||||
key, wasV2, err = km.unwrapKEK(entry.Content)
|
||||
if err == nil {
|
||||
// Successful unwrap: if the payload was the legacy fixed-salt
|
||||
// format, opportunistically rewrap it under a fresh per-installation
|
||||
// salt so the next restart picks up the stronger format. The
|
||||
// version flag comes straight out of unwrapKEK, avoiding a second
|
||||
// base64 decode pass over the same content.
|
||||
if !wasV2 {
|
||||
if rewrapped, wrapErr := km.wrapKEK(key); wrapErr != nil {
|
||||
glog.Warningf("SSE-S3 KeyManager: failed to rewrap legacy fixed-salt KEK to v2: %v", wrapErr)
|
||||
} else if updErr := km.updateKEKContent(rewrapped); updErr != nil {
|
||||
glog.Warningf("SSE-S3 KeyManager: failed to persist v2-rewrapped KEK: %v", updErr)
|
||||
} else {
|
||||
glog.V(1).Infof("SSE-S3 KeyManager: migrated KEK from fixed-salt v1 to per-installation salt v2")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Fall back: maybe this is a legacy plaintext hex KEK — try to decode and re-wrap
|
||||
legacyKey, hexErr := hex.DecodeString(string(entry.Content))
|
||||
if hexErr != nil || len(legacyKey) != SSES3KeySize {
|
||||
return fmt.Errorf("failed to unwrap KEK: %w", err)
|
||||
}
|
||||
glog.Warningf("SSE-S3 KeyManager: migrating plaintext KEK to encrypted storage")
|
||||
key = legacyKey
|
||||
// Re-save in encrypted form. Both failure modes used to be swallowed,
|
||||
// which left the KEK on disk in plaintext while startup proceeded —
|
||||
// an operator setting a passphrase saw a silent no-op and no signal
|
||||
// that the migration had failed. Log loudly so the next restart
|
||||
// makes the unmigrated state obvious; we still load the in-memory
|
||||
// key so the server stays up.
|
||||
wrapped, wrapErr := km.wrapKEK(key)
|
||||
if wrapErr != nil {
|
||||
glog.Errorf("SSE-S3 KeyManager: failed to wrap legacy KEK during migration; KEK remains plaintext on filer: %v", wrapErr)
|
||||
} else if updErr := km.updateKEKContent(wrapped); updErr != nil {
|
||||
glog.Errorf("SSE-S3 KeyManager: failed to persist wrapped KEK during migration; KEK remains plaintext on filer: %v", updErr)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Legacy plaintext hex mode
|
||||
glog.Warningf("SSE-S3 KeyManager: KEK stored in plaintext — set a KEK passphrase for encrypted storage")
|
||||
key, err = hex.DecodeString(string(entry.Content))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode KEK: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(key) != SSES3KeySize {
|
||||
@@ -447,6 +651,57 @@ func (km *SSES3KeyManager) loadSuperKeyFromFiler() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// updateKEKContent overwrites the existing KEK file content in the filer.
|
||||
// Used by the plaintext→encrypted migration path and by the v1→v2 salt
|
||||
// rewrap; both run after a successful read of the current KEK, so the
|
||||
// entry is guaranteed to exist. MkFile uses CreateEntry which fails with
|
||||
// ErrEntryAlreadyExists when the file is already there — we need
|
||||
// UpdateEntry instead so the migration actually persists.
|
||||
//
|
||||
// Splits km.kekPath at the last "/" so an operator-overridden path is
|
||||
// honoured. Defaults match defaultKEKPath when km.kekPath is unset.
|
||||
func (km *SSES3KeyManager) updateKEKContent(content []byte) error {
|
||||
dir, name := splitKEKPath(km.kekPath)
|
||||
ctx := context.Background()
|
||||
return km.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.LookupDirectoryEntry(ctx, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: dir,
|
||||
Name: name,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("lookup KEK entry: %w", err)
|
||||
}
|
||||
entry := resp.Entry
|
||||
if entry == nil {
|
||||
return fmt.Errorf("KEK entry not found at %s/%s", dir, name)
|
||||
}
|
||||
entry.Content = content
|
||||
if entry.Attributes == nil {
|
||||
entry.Attributes = &filer_pb.FuseAttributes{}
|
||||
}
|
||||
entry.Attributes.FileMode = 0600
|
||||
entry.Attributes.FileSize = uint64(len(content))
|
||||
entry.Attributes.Mtime = time.Now().Unix()
|
||||
return filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{
|
||||
Directory: dir,
|
||||
Entry: entry,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// splitKEKPath splits an absolute KEK file path into (directory, name).
|
||||
// Falls back to the default location if the path is empty or has no slash.
|
||||
func splitKEKPath(p string) (dir, name string) {
|
||||
if p == "" {
|
||||
return SSES3KEKDirectory, SSES3KEKFileName
|
||||
}
|
||||
idx := strings.LastIndex(p, "/")
|
||||
if idx <= 0 {
|
||||
return SSES3KEKDirectory, SSES3KEKFileName
|
||||
}
|
||||
return p[:idx], p[idx+1:]
|
||||
}
|
||||
|
||||
// GetOrCreateKey gets an existing key or creates a new one
|
||||
// With envelope encryption, we always generate a new DEK since we don't store them
|
||||
func (km *SSES3KeyManager) GetOrCreateKey(keyID string) (*SSES3Key, error) {
|
||||
@@ -545,9 +800,26 @@ func (km *SSES3KeyManager) GetMasterKey() []byte {
|
||||
return derived
|
||||
}
|
||||
|
||||
// SSES3KEKPassphraseEnv is the legacy environment variable from which the
|
||||
// global SSE-S3 key manager picks up its KEK-wrapping passphrase. The Viper
|
||||
// config key sseS3KEKPassphraseConfigKey ("s3.sse.kek.passphrase") is the
|
||||
// preferred way to set it — same precedence as s3.sse.kek and s3.sse.key —
|
||||
// but the env var is honoured as a fallback so deployments that wired only
|
||||
// the env keep working.
|
||||
const SSES3KEKPassphraseEnv = "WEED_S3_SSE_KEK_PASSPHRASE"
|
||||
|
||||
// Global SSE-S3 key manager instance
|
||||
var globalSSES3KeyManager = NewSSES3KeyManager()
|
||||
|
||||
// SetKEKPassphrase configures the KEK-wrapping passphrase. Must be called
|
||||
// before InitializeWithFiler — the load path reads the passphrase to decide
|
||||
// whether to attempt unwrap or fall back to plaintext-hex parsing.
|
||||
func (km *SSES3KeyManager) SetKEKPassphrase(passphrase string) {
|
||||
km.mu.Lock()
|
||||
defer km.mu.Unlock()
|
||||
km.kekPassphrase = passphrase
|
||||
}
|
||||
|
||||
// GetSSES3KeyManager returns the global SSE-S3 key manager
|
||||
func GetSSES3KeyManager() *SSES3KeyManager {
|
||||
return globalSSES3KeyManager
|
||||
@@ -571,8 +843,25 @@ func (k *KeyManagerFilerClient) WithFilerClient(streamingMode bool, fn func(file
|
||||
return pb.WithGrpcFilerClient(streamingMode, 0, filerAddress, k.grpcDialOption, fn)
|
||||
}
|
||||
|
||||
// InitializeGlobalSSES3KeyManager initializes the global key manager with filer access
|
||||
// InitializeGlobalSSES3KeyManager initializes the global key manager with
|
||||
// filer access. The KEK-wrapping passphrase is sourced from the Viper
|
||||
// config key s3.sse.kek.passphrase (matching the s3.sse.kek and
|
||||
// s3.sse.key conventions, settable via security.toml or
|
||||
// WEED_S3_SSE_KEK_PASSPHRASE env), with a fallback to the bare
|
||||
// SSES3KEKPassphraseEnv lookup for deployments wired before the Viper key
|
||||
// existed. If neither is set the KEK falls back to plaintext at-rest
|
||||
// storage (with a startup warning).
|
||||
func InitializeGlobalSSES3KeyManager(filerClient *wdclient.FilerClient, grpcDialOption grpc.DialOption) error {
|
||||
passphrase := util.GetViper().GetString(sseS3KEKPassphraseConfigKey)
|
||||
if passphrase == "" {
|
||||
passphrase = os.Getenv(SSES3KEKPassphraseEnv)
|
||||
}
|
||||
if passphrase != "" {
|
||||
globalSSES3KeyManager.SetKEKPassphrase(passphrase)
|
||||
} else {
|
||||
glog.Warningf("SSE-S3 KeyManager: neither %s nor %s is set; the KEK will be stored on the filer in plaintext. Set one to enable encrypted-at-rest KEK storage.", sseS3KEKPassphraseConfigKey, SSES3KEKPassphraseEnv)
|
||||
}
|
||||
|
||||
wrapper := &KeyManagerFilerClient{
|
||||
FilerClient: filerClient,
|
||||
grpcDialOption: grpcDialOption,
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestSetKEKPassphraseEnablesEncryptedRoundTrip exercises the wrap/unwrap
|
||||
// round-trip after SetKEKPassphrase configures the manager. This is the
|
||||
// primary behaviour the new env-var wiring relies on: once the passphrase
|
||||
// is in place, wrapKEK produces v2-format ciphertext that unwrapKEK can
|
||||
// reverse. Without the SetKEKPassphrase plumbing, deriveWrappingKey would
|
||||
// fail with "no KEK passphrase configured".
|
||||
func TestSetKEKPassphraseEnablesEncryptedRoundTrip(t *testing.T) {
|
||||
km := NewSSES3KeyManager()
|
||||
km.SetKEKPassphrase("test-passphrase-32-bytes-or-anything")
|
||||
|
||||
original := make([]byte, SSES3KeySize)
|
||||
for i := range original {
|
||||
original[i] = byte(i)
|
||||
}
|
||||
|
||||
wrapped, err := km.wrapKEK(original)
|
||||
if err != nil {
|
||||
t.Fatalf("wrapKEK: %v", err)
|
||||
}
|
||||
|
||||
got, isV2, err := km.unwrapKEK(wrapped)
|
||||
if err != nil {
|
||||
t.Fatalf("unwrapKEK: %v", err)
|
||||
}
|
||||
if !isV2 {
|
||||
t.Fatal("wrapped output should be reported as v2 by unwrapKEK")
|
||||
}
|
||||
if string(got) != string(original) {
|
||||
t.Fatalf("round-trip mismatch: got %x want %x", got, original)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetKEKPassphraseDifferentInstancesNoCollision proves random salts
|
||||
// per-installation actually decorrelate two managers using the same
|
||||
// passphrase: their wrapped payloads must differ even when the input KEK
|
||||
// matches.
|
||||
func TestSetKEKPassphraseDifferentInstancesNoCollision(t *testing.T) {
|
||||
a := NewSSES3KeyManager()
|
||||
a.SetKEKPassphrase("shared-passphrase")
|
||||
b := NewSSES3KeyManager()
|
||||
b.SetKEKPassphrase("shared-passphrase")
|
||||
|
||||
kek := make([]byte, SSES3KeySize)
|
||||
for i := range kek {
|
||||
kek[i] = 0xAB
|
||||
}
|
||||
|
||||
wa, err := a.wrapKEK(kek)
|
||||
if err != nil {
|
||||
t.Fatalf("wrapKEK a: %v", err)
|
||||
}
|
||||
wb, err := b.wrapKEK(kek)
|
||||
if err != nil {
|
||||
t.Fatalf("wrapKEK b: %v", err)
|
||||
}
|
||||
if string(wa) == string(wb) {
|
||||
t.Fatal("two managers with the same passphrase produced byte-identical wrapped output; salt is not random")
|
||||
}
|
||||
|
||||
// Both must still self-roundtrip.
|
||||
if got, _, _ := a.unwrapKEK(wa); string(got) != string(kek) {
|
||||
t.Fatal("manager a failed self roundtrip")
|
||||
}
|
||||
if got, _, _ := b.unwrapKEK(wb); string(got) != string(kek) {
|
||||
t.Fatal("manager b failed self roundtrip")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNoPassphraseKeepsLegacyHexDecodePath confirms that a manager left
|
||||
// without a passphrase still drives the historical plaintext-hex path
|
||||
// (loadSuperKeyFromFiler logs a warning and reads hex). That's the
|
||||
// fallback InitializeGlobalSSES3KeyManager keeps for upgrades.
|
||||
func TestNoPassphraseKeepsLegacyHexDecodePath(t *testing.T) {
|
||||
km := NewSSES3KeyManager()
|
||||
if km.kekPassphrase != "" {
|
||||
t.Fatalf("default passphrase should be empty, got %q", km.kekPassphrase)
|
||||
}
|
||||
// wrapKEK requires a passphrase; without one it must surface the error
|
||||
// rather than producing unencrypted output.
|
||||
if _, err := km.wrapKEK(make([]byte, SSES3KeySize)); err == nil {
|
||||
t.Fatal("wrapKEK without passphrase should fail; got nil error")
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,83 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// RequireKeyCommitmentEnv is the environment variable that flips the
|
||||
// commitment check from "skip when missing" (the AWS-compatible default,
|
||||
// needed for objects written before commitments shipped) to "reject when
|
||||
// missing". Operators who have either re-encrypted all legacy objects or
|
||||
// who never wrote any objects under the pre-commitment code path can opt
|
||||
// in via this env var to close the silent downgrade vector that an
|
||||
// attacker with write access to object metadata could otherwise exploit
|
||||
// by stripping the commitment field.
|
||||
const RequireKeyCommitmentEnv = "WEED_S3_REQUIRE_KEY_COMMITMENT"
|
||||
|
||||
// requireKeyCommitment is the runtime mirror of the env var, kept as an
|
||||
// atomic so config-reload paths can flip it without a global mutex.
|
||||
var requireKeyCommitment atomic.Bool
|
||||
|
||||
func init() {
|
||||
if v := os.Getenv(RequireKeyCommitmentEnv); v == "1" || strings.EqualFold(v, "true") {
|
||||
requireKeyCommitment.Store(true)
|
||||
glog.V(1).Infof("SSE: %s=true; SSE objects without a key commitment will be rejected", RequireKeyCommitmentEnv)
|
||||
}
|
||||
}
|
||||
|
||||
// SetRequireKeyCommitment toggles strict-commitment enforcement at runtime.
|
||||
// Used by tests and by future config-reload code paths.
|
||||
func SetRequireKeyCommitment(require bool) {
|
||||
requireKeyCommitment.Store(require)
|
||||
}
|
||||
|
||||
// ComputeKeyCommitment computes an HMAC-SHA256 key commitment over the
|
||||
// encryption parameters (IV + algorithm). This binds the ciphertext to the
|
||||
// exact key material and IV that were used, preventing key-confusion and
|
||||
// IV-manipulation attacks against unauthenticated AES-CTR.
|
||||
//
|
||||
// The commitment is stored alongside the IV in object metadata. On decrypt
|
||||
// the commitment is re-derived and compared; a mismatch means the key or IV
|
||||
// was tampered with.
|
||||
func ComputeKeyCommitment(key []byte, iv []byte, algorithm string) []byte {
|
||||
mac := hmac.New(sha256.New, key)
|
||||
mac.Write(iv)
|
||||
mac.Write([]byte(algorithm))
|
||||
return mac.Sum(nil)
|
||||
}
|
||||
|
||||
// VerifyKeyCommitment checks a previously stored commitment against the
|
||||
// current key, IV, and algorithm. Returns nil on success.
|
||||
//
|
||||
// When the commitment is empty (legacy object written before commitments
|
||||
// shipped), the default behaviour is to accept the object — this is the
|
||||
// AWS-compatible path. Setting WEED_S3_REQUIRE_KEY_COMMITMENT=true (via
|
||||
// env at startup or via SetRequireKeyCommitment at runtime) flips that
|
||||
// to reject, closing the silent-downgrade vector at the cost of locking
|
||||
// out un-migrated legacy objects.
|
||||
func VerifyKeyCommitment(key []byte, iv []byte, algorithm string, commitment []byte) error {
|
||||
if len(commitment) == 0 {
|
||||
if requireKeyCommitment.Load() {
|
||||
return fmt.Errorf("key commitment is required but missing from object metadata: %s set; legacy objects must be re-encrypted before this flag can be enabled", RequireKeyCommitmentEnv)
|
||||
}
|
||||
// Legacy data written before key commitments were added; skip.
|
||||
return nil
|
||||
}
|
||||
expected := ComputeKeyCommitment(key, iv, algorithm)
|
||||
if !hmac.Equal(expected, commitment) {
|
||||
return fmt.Errorf("key commitment verification failed: encryption parameters may have been tampered with")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// isValidKMSKeyID performs basic validation of KMS key identifiers.
|
||||
// Following Minio's approach: be permissive and accept any reasonable key format.
|
||||
// Only reject keys with leading/trailing spaces or other obvious issues.
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package s3api
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestVerifyKeyCommitment_DefaultAcceptsMissing(t *testing.T) {
|
||||
// Default behaviour mirrors AWS: a missing commitment field is treated
|
||||
// as a legacy object and accepted. This is the cushion that lets
|
||||
// operators upgrade without breaking pre-commitment uploads.
|
||||
prev := requireKeyCommitment.Load()
|
||||
t.Cleanup(func() { requireKeyCommitment.Store(prev) })
|
||||
requireKeyCommitment.Store(false)
|
||||
|
||||
if err := VerifyKeyCommitment([]byte("k"), []byte("iv"), "AES256", nil); err != nil {
|
||||
t.Fatalf("default path should accept missing commitment, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyKeyCommitment_StrictRejectsMissing(t *testing.T) {
|
||||
// Strict mode: any object whose metadata lacks the commitment field is
|
||||
// rejected. Closes the silent-downgrade vector — an attacker who can
|
||||
// strip the commitment from metadata can no longer bypass verification.
|
||||
prev := requireKeyCommitment.Load()
|
||||
t.Cleanup(func() { requireKeyCommitment.Store(prev) })
|
||||
requireKeyCommitment.Store(true)
|
||||
|
||||
err := VerifyKeyCommitment([]byte("k"), []byte("iv"), "AES256", nil)
|
||||
if err == nil {
|
||||
t.Fatal("strict mode should reject missing commitment; got nil error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyKeyCommitment_StrictAcceptsValidCommitment(t *testing.T) {
|
||||
// Strict mode does not change the verification outcome for objects that
|
||||
// do carry a commitment — the only behavioural delta is the missing
|
||||
// case.
|
||||
prev := requireKeyCommitment.Load()
|
||||
t.Cleanup(func() { requireKeyCommitment.Store(prev) })
|
||||
requireKeyCommitment.Store(true)
|
||||
|
||||
key := []byte("strict-mode-test-key")
|
||||
// IV here is just an opaque input to the HMAC commitment; the test
|
||||
// doesn't pass it into AES-CTR so it doesn't have to be the AES block
|
||||
// size. The 16 bytes match the AES block size to keep the literal
|
||||
// realistic.
|
||||
iv := []byte("strict-mode-iv16")
|
||||
commit := ComputeKeyCommitment(key, iv, "AES256")
|
||||
if err := VerifyKeyCommitment(key, iv, "AES256", commit); err != nil {
|
||||
t.Fatalf("strict mode should accept valid commitment, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyKeyCommitment_RejectsTamperedKey(t *testing.T) {
|
||||
// Real attack shape: an attacker who can mutate object metadata cannot
|
||||
// craft a valid commitment without the original key. The verify path
|
||||
// must catch it whether they tamper with the key, the IV, or the
|
||||
// algorithm — all three are bound by the HMAC.
|
||||
prev := requireKeyCommitment.Load()
|
||||
t.Cleanup(func() { requireKeyCommitment.Store(prev) })
|
||||
requireKeyCommitment.Store(false)
|
||||
|
||||
originalKey := []byte("legit-key-for-commitment")
|
||||
iv := []byte("commitment-iv-16")
|
||||
algo := "AES256"
|
||||
commit := ComputeKeyCommitment(originalKey, iv, algo)
|
||||
|
||||
t.Run("tampered key", func(t *testing.T) {
|
||||
if err := VerifyKeyCommitment([]byte("attacker-substituted-key"), iv, algo, commit); err == nil {
|
||||
t.Fatal("verify must reject when the key changed but commitment did not")
|
||||
}
|
||||
})
|
||||
t.Run("tampered IV", func(t *testing.T) {
|
||||
if err := VerifyKeyCommitment(originalKey, []byte("attacker-iv-16!!"), algo, commit); err == nil {
|
||||
t.Fatal("verify must reject when the IV changed but commitment did not")
|
||||
}
|
||||
})
|
||||
t.Run("tampered algorithm", func(t *testing.T) {
|
||||
if err := VerifyKeyCommitment(originalKey, iv, "AES128", commit); err == nil {
|
||||
t.Fatal("verify must reject when the algorithm changed but commitment did not")
|
||||
}
|
||||
})
|
||||
t.Run("tampered commitment", func(t *testing.T) {
|
||||
bad := append([]byte{}, commit...)
|
||||
bad[0] ^= 0x01
|
||||
if err := VerifyKeyCommitment(originalKey, iv, algo, bad); err == nil {
|
||||
t.Fatal("verify must reject when the commitment itself was flipped")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSetRequireKeyCommitment(t *testing.T) {
|
||||
prev := requireKeyCommitment.Load()
|
||||
t.Cleanup(func() { requireKeyCommitment.Store(prev) })
|
||||
|
||||
SetRequireKeyCommitment(true)
|
||||
if !requireKeyCommitment.Load() {
|
||||
t.Fatal("SetRequireKeyCommitment(true) did not propagate to the atomic")
|
||||
}
|
||||
SetRequireKeyCommitment(false)
|
||||
if requireKeyCommitment.Load() {
|
||||
t.Fatal("SetRequireKeyCommitment(false) did not propagate to the atomic")
|
||||
}
|
||||
}
|
||||
@@ -2165,13 +2165,24 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
|
||||
if e.readOnly {
|
||||
switch action {
|
||||
case "ListUsers", "ListAccessKeys", "GetUser", "GetUserPolicy", "ListUserPolicies", "ListAttachedUserPolicies", "ListPolicies", "GetPolicy", "ListPolicyVersions", "GetPolicyVersion", "ListServiceAccounts", "GetServiceAccount",
|
||||
"GetGroup", "ListGroups", "ListAttachedGroupPolicies", "GetGroupPolicy", "ListGroupPolicies", "ListGroupsForUser":
|
||||
"GetGroup", "ListGroups", "ListAttachedGroupPolicies", "GetGroupPolicy", "ListGroupPolicies", "ListGroupsForUser",
|
||||
actionListOpenIDConnectProviders, actionGetOpenIDConnectProvider:
|
||||
// Allowed read-only actions
|
||||
default:
|
||||
return nil, &iamError{Code: s3err.GetAPIError(s3err.ErrAccessDenied).Code, Error: fmt.Errorf("IAM write operations are disabled on this server")}
|
||||
}
|
||||
}
|
||||
|
||||
// OIDC provider actions don't operate on S3ApiConfiguration; dispatch
|
||||
// before the unrelated config load + reload churn.
|
||||
if response, iamErr, ok := e.dispatchOIDCProviderAction(ctx, values); ok {
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
response.SetRequestId(reqID)
|
||||
return response, nil
|
||||
}
|
||||
|
||||
s3cfg := &iam_pb.S3ApiConfiguration{}
|
||||
if err := e.GetS3ApiConfiguration(s3cfg); err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil, &iamError{Code: s3err.GetAPIError(s3err.ErrInternalError).Code, Error: fmt.Errorf("failed to get s3 api configuration: %v", err)}
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
iamlib "github.com/seaweedfs/seaweedfs/weed/iam"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
)
|
||||
|
||||
// OIDC provider IAM actions handled by this file.
|
||||
const (
|
||||
actionGetOpenIDConnectProvider = "GetOpenIDConnectProvider"
|
||||
actionListOpenIDConnectProviders = "ListOpenIDConnectProviders"
|
||||
actionCreateOpenIDConnectProvider = "CreateOpenIDConnectProvider"
|
||||
actionDeleteOpenIDConnectProvider = "DeleteOpenIDConnectProvider"
|
||||
actionAddClientIDToOpenIDConnectProvider = "AddClientIDToOpenIDConnectProvider"
|
||||
actionRemoveClientIDFromOpenIDConnectProvider = "RemoveClientIDFromOpenIDConnectProvider"
|
||||
actionUpdateOpenIDConnectProviderThumbprint = "UpdateOpenIDConnectProviderThumbprint"
|
||||
actionTagOpenIDConnectProvider = "TagOpenIDConnectProvider"
|
||||
actionUntagOpenIDConnectProvider = "UntagOpenIDConnectProvider"
|
||||
)
|
||||
|
||||
// isOIDCProviderAction reports whether an action belongs to the OIDC provider
|
||||
// family. Used by ExecuteAction to short-circuit the S3ApiConfiguration code
|
||||
// path for actions that don't operate on it.
|
||||
func isOIDCProviderAction(action string) bool {
|
||||
switch action {
|
||||
case actionGetOpenIDConnectProvider,
|
||||
actionListOpenIDConnectProviders,
|
||||
actionCreateOpenIDConnectProvider,
|
||||
actionDeleteOpenIDConnectProvider,
|
||||
actionAddClientIDToOpenIDConnectProvider,
|
||||
actionRemoveClientIDFromOpenIDConnectProvider,
|
||||
actionUpdateOpenIDConnectProviderThumbprint,
|
||||
actionTagOpenIDConnectProvider,
|
||||
actionUntagOpenIDConnectProvider:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// dispatchOIDCProviderAction handles the OIDC provider IAM actions. Returns a
|
||||
// response, the IAM error if any, and a boolean indicating whether the action
|
||||
// was recognised (so the caller can fall through when false).
|
||||
func (e *EmbeddedIamApi) dispatchOIDCProviderAction(ctx context.Context, values url.Values) (iamlib.RequestIDSetter, *iamError, bool) {
|
||||
if !isOIDCProviderAction(values.Get("Action")) {
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
mgr := e.oidcIAMManager()
|
||||
if mgr == nil {
|
||||
return nil, &iamError{
|
||||
Code: iam.ErrCodeServiceFailureException,
|
||||
Error: errors.New("OIDC provider store not configured"),
|
||||
}, true
|
||||
}
|
||||
|
||||
switch values.Get("Action") {
|
||||
case actionListOpenIDConnectProviders:
|
||||
resp, err := e.listOpenIDConnectProviders(ctx, mgr)
|
||||
return resp, err, true
|
||||
case actionGetOpenIDConnectProvider:
|
||||
resp, err := e.getOpenIDConnectProvider(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionCreateOpenIDConnectProvider:
|
||||
resp, err := e.createOpenIDConnectProvider(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionDeleteOpenIDConnectProvider:
|
||||
resp, err := e.deleteOpenIDConnectProvider(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionAddClientIDToOpenIDConnectProvider:
|
||||
resp, err := e.addClientIDToOpenIDConnectProvider(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionRemoveClientIDFromOpenIDConnectProvider:
|
||||
resp, err := e.removeClientIDFromOpenIDConnectProvider(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionUpdateOpenIDConnectProviderThumbprint:
|
||||
resp, err := e.updateOpenIDConnectProviderThumbprint(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionTagOpenIDConnectProvider:
|
||||
resp, err := e.tagOpenIDConnectProvider(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionUntagOpenIDConnectProvider:
|
||||
resp, err := e.untagOpenIDConnectProvider(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
// extractMemberList collects all values from `Foo.member.<n>=...` form
|
||||
// parameters in order of N. AWS query-string conventions encode list inputs
|
||||
// this way, so List/Add/Update/Tag actions all share this helper.
|
||||
func extractMemberList(values url.Values, prefix string) []string {
|
||||
out := []string{}
|
||||
// Members are indexed from 1; iterate until a missing index breaks the run.
|
||||
for i := 1; ; i++ {
|
||||
key := fmt.Sprintf("%s.member.%d", prefix, i)
|
||||
v := values.Get(key)
|
||||
if v == "" {
|
||||
break
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) createOpenIDConnectProvider(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.CreateOpenIDConnectProviderResponse, *iamError) {
|
||||
urlStr := strings.TrimSpace(values.Get("Url"))
|
||||
if urlStr == "" {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("Url is required")}
|
||||
}
|
||||
clientIDs := extractMemberList(values, "ClientIDList")
|
||||
if len(clientIDs) == 0 {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("ClientIDList must contain at least one entry")}
|
||||
}
|
||||
thumbprints := extractMemberList(values, "ThumbprintList")
|
||||
tags := extractTags(values)
|
||||
|
||||
accountID := mgr.GetSTSService().Config.AccountId
|
||||
arn, err := integration.DeriveOIDCProviderARN(accountID, urlStr)
|
||||
if err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: err}
|
||||
}
|
||||
|
||||
rec := &integration.OIDCProviderRecord{
|
||||
AccountID: accountID,
|
||||
ARN: arn,
|
||||
URL: urlStr,
|
||||
ClientIDs: clientIDs,
|
||||
Thumbprints: thumbprints,
|
||||
Tags: tags,
|
||||
}
|
||||
if err := mgr.CreateOIDCProvider(ctx, rec); err != nil {
|
||||
if errors.Is(err, integration.ErrOIDCProviderAlreadyExists) {
|
||||
return nil, &iamError{Code: iam.ErrCodeEntityAlreadyExistsException, Error: err}
|
||||
}
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: err}
|
||||
}
|
||||
|
||||
resp := &iamlib.CreateOpenIDConnectProviderResponse{}
|
||||
resp.CreateOpenIDConnectProviderResult.OpenIDConnectProviderArn = rec.ARN
|
||||
if len(rec.Tags) > 0 {
|
||||
out := make([]*iamlib.IAMTag, 0, len(rec.Tags))
|
||||
for k, v := range rec.Tags {
|
||||
out = append(out, &iamlib.IAMTag{Key: k, Value: v})
|
||||
}
|
||||
resp.CreateOpenIDConnectProviderResult.Tags = out
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) deleteOpenIDConnectProvider(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.DeleteOpenIDConnectProviderResponse, *iamError) {
|
||||
arn, iamErr := requireProviderArn(values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
if err := mgr.DeleteOIDCProvider(ctx, arn); err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
return &iamlib.DeleteOpenIDConnectProviderResponse{}, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) addClientIDToOpenIDConnectProvider(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.AddClientIDToOpenIDConnectProviderResponse, *iamError) {
|
||||
arn, iamErr := requireProviderArn(values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
clientID := strings.TrimSpace(values.Get("ClientID"))
|
||||
if clientID == "" {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("ClientID is required")}
|
||||
}
|
||||
if err := mgr.AddClientIDToOIDCProvider(ctx, arn, clientID); err != nil {
|
||||
if errors.Is(err, integration.ErrOIDCProviderNotFound) {
|
||||
return nil, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: err}
|
||||
}
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
return &iamlib.AddClientIDToOpenIDConnectProviderResponse{}, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) removeClientIDFromOpenIDConnectProvider(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.RemoveClientIDFromOpenIDConnectProviderResponse, *iamError) {
|
||||
arn, iamErr := requireProviderArn(values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
clientID := strings.TrimSpace(values.Get("ClientID"))
|
||||
if clientID == "" {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("ClientID is required")}
|
||||
}
|
||||
if err := mgr.RemoveClientIDFromOIDCProvider(ctx, arn, clientID); err != nil {
|
||||
if errors.Is(err, integration.ErrOIDCProviderNotFound) {
|
||||
return nil, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: err}
|
||||
}
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
return &iamlib.RemoveClientIDFromOpenIDConnectProviderResponse{}, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) updateOpenIDConnectProviderThumbprint(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.UpdateOpenIDConnectProviderThumbprintResponse, *iamError) {
|
||||
arn, iamErr := requireProviderArn(values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
thumbprints := extractMemberList(values, "ThumbprintList")
|
||||
if len(thumbprints) == 0 {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("ThumbprintList must contain at least one entry")}
|
||||
}
|
||||
if err := mgr.UpdateOIDCProviderThumbprints(ctx, arn, thumbprints); err != nil {
|
||||
if errors.Is(err, integration.ErrOIDCProviderNotFound) {
|
||||
return nil, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: err}
|
||||
}
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: err}
|
||||
}
|
||||
return &iamlib.UpdateOpenIDConnectProviderThumbprintResponse{}, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) tagOpenIDConnectProvider(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.TagOpenIDConnectProviderResponse, *iamError) {
|
||||
arn, iamErr := requireProviderArn(values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
tags := extractTags(values)
|
||||
if len(tags) == 0 {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("Tags must contain at least one Key/Value pair")}
|
||||
}
|
||||
if err := mgr.TagOIDCProvider(ctx, arn, tags); err != nil {
|
||||
if errors.Is(err, integration.ErrOIDCProviderNotFound) {
|
||||
return nil, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: err}
|
||||
}
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
return &iamlib.TagOpenIDConnectProviderResponse{}, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) untagOpenIDConnectProvider(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.UntagOpenIDConnectProviderResponse, *iamError) {
|
||||
arn, iamErr := requireProviderArn(values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
keys := extractMemberList(values, "TagKeys")
|
||||
if len(keys) == 0 {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("TagKeys must contain at least one entry")}
|
||||
}
|
||||
if err := mgr.UntagOIDCProvider(ctx, arn, keys); err != nil {
|
||||
if errors.Is(err, integration.ErrOIDCProviderNotFound) {
|
||||
return nil, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: err}
|
||||
}
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
return &iamlib.UntagOpenIDConnectProviderResponse{}, nil
|
||||
}
|
||||
|
||||
// extractTags walks the AWS IAM "Tags.member.N.Key / Tags.member.N.Value"
|
||||
// query-string convention and returns the parsed map. Returns nil (not an
|
||||
// empty map) when no tags are present so the caller can distinguish
|
||||
// "untouched" from "empty".
|
||||
func extractTags(values url.Values) map[string]string {
|
||||
var out map[string]string
|
||||
for i := 1; ; i++ {
|
||||
k := values.Get(fmt.Sprintf("Tags.member.%d.Key", i))
|
||||
if k == "" {
|
||||
break
|
||||
}
|
||||
if out == nil {
|
||||
out = make(map[string]string)
|
||||
}
|
||||
out[k] = values.Get(fmt.Sprintf("Tags.member.%d.Value", i))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func requireProviderArn(values url.Values) (string, *iamError) {
|
||||
arn := strings.TrimSpace(values.Get("OpenIDConnectProviderArn"))
|
||||
if arn == "" {
|
||||
return "", &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("OpenIDConnectProviderArn is required")}
|
||||
}
|
||||
return arn, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) oidcIAMManager() *integration.IAMManager {
|
||||
if e.iam == nil || e.iam.iamIntegration == nil {
|
||||
return nil
|
||||
}
|
||||
provider, ok := e.iam.iamIntegration.(IAMManagerProvider)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return provider.GetIAMManager()
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) listOpenIDConnectProviders(ctx context.Context, mgr *integration.IAMManager) (*iamlib.ListOpenIDConnectProvidersResponse, *iamError) {
|
||||
records, err := mgr.ListOIDCProviders(ctx)
|
||||
if err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
resp := &iamlib.ListOpenIDConnectProvidersResponse{}
|
||||
resp.ListOpenIDConnectProvidersResult.OpenIDConnectProviderList = make([]*iamlib.OpenIDConnectProviderListEntry, 0, len(records))
|
||||
for _, rec := range records {
|
||||
resp.ListOpenIDConnectProvidersResult.OpenIDConnectProviderList = append(
|
||||
resp.ListOpenIDConnectProvidersResult.OpenIDConnectProviderList,
|
||||
&iamlib.OpenIDConnectProviderListEntry{Arn: rec.ARN},
|
||||
)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) getOpenIDConnectProvider(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.GetOpenIDConnectProviderResponse, *iamError) {
|
||||
arn := strings.TrimSpace(values.Get("OpenIDConnectProviderArn"))
|
||||
if arn == "" {
|
||||
return nil, &iamError{
|
||||
Code: iam.ErrCodeInvalidInputException,
|
||||
Error: fmt.Errorf("OpenIDConnectProviderArn is required"),
|
||||
}
|
||||
}
|
||||
rec, err := mgr.GetOIDCProvider(ctx, arn)
|
||||
if err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: err}
|
||||
}
|
||||
resp := &iamlib.GetOpenIDConnectProviderResponse{}
|
||||
resp.GetOpenIDConnectProviderResult.Url = rec.URL
|
||||
resp.GetOpenIDConnectProviderResult.ClientIDList = append([]string(nil), rec.ClientIDs...)
|
||||
resp.GetOpenIDConnectProviderResult.ThumbprintList = append([]string(nil), rec.Thumbprints...)
|
||||
if !rec.CreatedAt.IsZero() {
|
||||
// AWS uses ISO-8601; the IAM XML format accepts time.Time-string output.
|
||||
resp.GetOpenIDConnectProviderResult.CreateDate = rec.CreatedAt.UTC().Format("2006-01-02T15:04:05Z")
|
||||
}
|
||||
if len(rec.Tags) > 0 {
|
||||
tags := make([]*iamlib.IAMTag, 0, len(rec.Tags))
|
||||
for k, v := range rec.Tags {
|
||||
tags = append(tags, &iamlib.IAMTag{Key: k, Value: v})
|
||||
}
|
||||
resp.GetOpenIDConnectProviderResult.Tags = tags
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
iamlib "github.com/seaweedfs/seaweedfs/weed/iam"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
)
|
||||
|
||||
// stubIntegration is the smallest IAMManagerProvider that lets the OIDC
|
||||
// dispatcher reach an IAMManager. The other IAMIntegration methods are
|
||||
// unused by these tests and panic if invoked, which is what we want — any
|
||||
// unexpected call signals a routing bug.
|
||||
type stubIntegration struct {
|
||||
IAMIntegration
|
||||
mgr *integration.IAMManager
|
||||
}
|
||||
|
||||
func (s *stubIntegration) GetIAMManager() *integration.IAMManager { return s.mgr }
|
||||
|
||||
func newOIDCTestAPI(t *testing.T) (*EmbeddedIamApiForTest, *integration.IAMManager) {
|
||||
t.Helper()
|
||||
mgr := integration.NewIAMManager()
|
||||
cfg := &integration.IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test-sts",
|
||||
SigningKey: []byte("test-signing-key-32-characters-long"),
|
||||
AccountId: "111122223333",
|
||||
Providers: []*sts.ProviderConfig{
|
||||
{
|
||||
Name: "google",
|
||||
Type: sts.ProviderTypeOIDC,
|
||||
Enabled: true,
|
||||
Config: map[string]interface{}{
|
||||
"issuer": "https://accounts.google.com",
|
||||
"clientId": "client-google",
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "github",
|
||||
Type: sts.ProviderTypeOIDC,
|
||||
Enabled: true,
|
||||
Config: map[string]interface{}{
|
||||
"issuer": "https://token.actions.githubusercontent.com",
|
||||
"clientId": "sts.amazonaws.com",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{DefaultEffect: "Deny", StoreType: "memory"},
|
||||
Roles: &integration.RoleStoreConfig{StoreType: "memory"},
|
||||
}
|
||||
if err := mgr.Initialize(cfg, func() string { return "localhost:8888" }); err != nil {
|
||||
t.Fatalf("Initialize IAM manager: %v", err)
|
||||
}
|
||||
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.iam.iamIntegration = &stubIntegration{mgr: mgr}
|
||||
return api, mgr
|
||||
}
|
||||
|
||||
func TestListOpenIDConnectProviders(t *testing.T) {
|
||||
api, _ := newOIDCTestAPI(t)
|
||||
values := url.Values{}
|
||||
values.Set("Action", actionListOpenIDConnectProviders)
|
||||
|
||||
resp, iamErr := api.ExecuteAction(context.Background(), values, true, "test-req-1")
|
||||
if iamErr != nil {
|
||||
t.Fatalf("ExecuteAction: code=%s err=%v", iamErr.Code, iamErr.Error)
|
||||
}
|
||||
listResp, ok := resp.(*iamlib.ListOpenIDConnectProvidersResponse)
|
||||
if !ok {
|
||||
t.Fatalf("unexpected response type %T", resp)
|
||||
}
|
||||
got := listResp.ListOpenIDConnectProvidersResult.OpenIDConnectProviderList
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("expected 2 providers, got %d", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOpenIDConnectProvider(t *testing.T) {
|
||||
api, _ := newOIDCTestAPI(t)
|
||||
arn := "arn:aws:iam::111122223333:oidc-provider/accounts.google.com"
|
||||
|
||||
values := url.Values{}
|
||||
values.Set("Action", actionGetOpenIDConnectProvider)
|
||||
values.Set("OpenIDConnectProviderArn", arn)
|
||||
|
||||
resp, iamErr := api.ExecuteAction(context.Background(), values, true, "test-req-2")
|
||||
if iamErr != nil {
|
||||
t.Fatalf("ExecuteAction: code=%s err=%v", iamErr.Code, iamErr.Error)
|
||||
}
|
||||
getResp, ok := resp.(*iamlib.GetOpenIDConnectProviderResponse)
|
||||
if !ok {
|
||||
t.Fatalf("unexpected response type %T", resp)
|
||||
}
|
||||
if getResp.GetOpenIDConnectProviderResult.Url != "https://accounts.google.com" {
|
||||
t.Fatalf("URL mismatch: %s", getResp.GetOpenIDConnectProviderResult.Url)
|
||||
}
|
||||
if len(getResp.GetOpenIDConnectProviderResult.ClientIDList) != 1 ||
|
||||
getResp.GetOpenIDConnectProviderResult.ClientIDList[0] != "client-google" {
|
||||
t.Fatalf("ClientIDList wrong: %v", getResp.GetOpenIDConnectProviderResult.ClientIDList)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOpenIDConnectProviderMissing(t *testing.T) {
|
||||
api, _ := newOIDCTestAPI(t)
|
||||
values := url.Values{}
|
||||
values.Set("Action", actionGetOpenIDConnectProvider)
|
||||
values.Set("OpenIDConnectProviderArn", "arn:aws:iam::111122223333:oidc-provider/nope.example")
|
||||
|
||||
_, iamErr := api.ExecuteAction(context.Background(), values, true, "test-req-3")
|
||||
if iamErr == nil {
|
||||
t.Fatal("expected NoSuchEntity error")
|
||||
}
|
||||
if iamErr.Code != "NoSuchEntity" {
|
||||
t.Fatalf("expected NoSuchEntity code, got %s", iamErr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOpenIDConnectProviderRequiresArn(t *testing.T) {
|
||||
api, _ := newOIDCTestAPI(t)
|
||||
values := url.Values{}
|
||||
values.Set("Action", actionGetOpenIDConnectProvider)
|
||||
|
||||
_, iamErr := api.ExecuteAction(context.Background(), values, true, "test-req-4")
|
||||
if iamErr == nil {
|
||||
t.Fatal("expected error for missing ARN")
|
||||
}
|
||||
if iamErr.Code != "InvalidInput" {
|
||||
t.Fatalf("expected InvalidInput code, got %s", iamErr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOnlyAllowsOIDCList(t *testing.T) {
|
||||
api, _ := newOIDCTestAPI(t)
|
||||
api.readOnly = true
|
||||
values := url.Values{}
|
||||
values.Set("Action", actionListOpenIDConnectProviders)
|
||||
|
||||
if _, iamErr := api.ExecuteAction(context.Background(), values, true, "ro-1"); iamErr != nil {
|
||||
t.Fatalf("read-only mode should allow ListOpenIDConnectProviders: %v", iamErr.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOnlyDeniesOIDCMutations(t *testing.T) {
|
||||
api, _ := newOIDCTestAPI(t)
|
||||
api.readOnly = true
|
||||
mutations := []string{
|
||||
actionCreateOpenIDConnectProvider,
|
||||
actionDeleteOpenIDConnectProvider,
|
||||
actionAddClientIDToOpenIDConnectProvider,
|
||||
actionRemoveClientIDFromOpenIDConnectProvider,
|
||||
actionUpdateOpenIDConnectProviderThumbprint,
|
||||
actionTagOpenIDConnectProvider,
|
||||
actionUntagOpenIDConnectProvider,
|
||||
}
|
||||
for _, action := range mutations {
|
||||
t.Run(action, func(t *testing.T) {
|
||||
values := url.Values{}
|
||||
values.Set("Action", action)
|
||||
_, iamErr := api.ExecuteAction(context.Background(), values, true, "ro-deny")
|
||||
if iamErr == nil {
|
||||
t.Fatalf("expected denial for %s in read-only mode", action)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateOpenIDConnectProvider(t *testing.T) {
|
||||
api, _ := newOIDCTestAPI(t)
|
||||
values := url.Values{}
|
||||
values.Set("Action", actionCreateOpenIDConnectProvider)
|
||||
values.Set("Url", "https://auth.example.com")
|
||||
values.Set("ClientIDList.member.1", "alpha")
|
||||
values.Set("ClientIDList.member.2", "beta")
|
||||
values.Set("ThumbprintList.member.1", "9e99a48a9960b14926bb7f3b02e22da2b0ab7280")
|
||||
values.Set("Tags.member.1.Key", "team")
|
||||
values.Set("Tags.member.1.Value", "infra")
|
||||
|
||||
resp, iamErr := api.ExecuteAction(context.Background(), values, true, "create-1")
|
||||
if iamErr != nil {
|
||||
t.Fatalf("ExecuteAction: %v", iamErr.Error)
|
||||
}
|
||||
createResp, ok := resp.(*iamlib.CreateOpenIDConnectProviderResponse)
|
||||
if !ok {
|
||||
t.Fatalf("unexpected response type %T", resp)
|
||||
}
|
||||
wantArn := "arn:aws:iam::111122223333:oidc-provider/auth.example.com"
|
||||
if createResp.CreateOpenIDConnectProviderResult.OpenIDConnectProviderArn != wantArn {
|
||||
t.Fatalf("ARN mismatch: got=%s want=%s",
|
||||
createResp.CreateOpenIDConnectProviderResult.OpenIDConnectProviderArn, wantArn)
|
||||
}
|
||||
|
||||
// Get the new provider back to confirm persistence and clientId list.
|
||||
getValues := url.Values{}
|
||||
getValues.Set("Action", actionGetOpenIDConnectProvider)
|
||||
getValues.Set("OpenIDConnectProviderArn", wantArn)
|
||||
getResp, iamErr := api.ExecuteAction(context.Background(), getValues, true, "get-after-create")
|
||||
if iamErr != nil {
|
||||
t.Fatalf("Get after create: %v", iamErr.Error)
|
||||
}
|
||||
gr := getResp.(*iamlib.GetOpenIDConnectProviderResponse).GetOpenIDConnectProviderResult
|
||||
if len(gr.ClientIDList) != 2 || gr.ClientIDList[0] != "alpha" || gr.ClientIDList[1] != "beta" {
|
||||
t.Fatalf("ClientIDList persisted incorrectly: %v", gr.ClientIDList)
|
||||
}
|
||||
if len(gr.ThumbprintList) != 1 || gr.ThumbprintList[0] != "9e99a48a9960b14926bb7f3b02e22da2b0ab7280" {
|
||||
t.Fatalf("ThumbprintList persisted incorrectly: %v", gr.ThumbprintList)
|
||||
}
|
||||
if len(gr.Tags) != 1 || gr.Tags[0].Key != "team" || gr.Tags[0].Value != "infra" {
|
||||
t.Fatalf("Tags persisted incorrectly: %v", gr.Tags)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateOpenIDConnectProviderRejectsBadInput(t *testing.T) {
|
||||
api, _ := newOIDCTestAPI(t)
|
||||
|
||||
t.Run("missing Url", func(t *testing.T) {
|
||||
values := url.Values{}
|
||||
values.Set("Action", actionCreateOpenIDConnectProvider)
|
||||
values.Set("ClientIDList.member.1", "x")
|
||||
_, iamErr := api.ExecuteAction(context.Background(), values, true, "")
|
||||
if iamErr == nil || iamErr.Code != "InvalidInput" {
|
||||
t.Fatalf("expected InvalidInput, got %v", iamErr)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing ClientIDList", func(t *testing.T) {
|
||||
values := url.Values{}
|
||||
values.Set("Action", actionCreateOpenIDConnectProvider)
|
||||
values.Set("Url", "https://auth.example.com")
|
||||
_, iamErr := api.ExecuteAction(context.Background(), values, true, "")
|
||||
if iamErr == nil || iamErr.Code != "InvalidInput" {
|
||||
t.Fatalf("expected InvalidInput, got %v", iamErr)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid thumbprint", func(t *testing.T) {
|
||||
values := url.Values{}
|
||||
values.Set("Action", actionCreateOpenIDConnectProvider)
|
||||
values.Set("Url", "https://auth.example.com")
|
||||
values.Set("ClientIDList.member.1", "x")
|
||||
values.Set("ThumbprintList.member.1", "not-a-sha1")
|
||||
_, iamErr := api.ExecuteAction(context.Background(), values, true, "")
|
||||
if iamErr == nil || iamErr.Code != "InvalidInput" {
|
||||
t.Fatalf("expected InvalidInput, got %v", iamErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCreateOpenIDConnectProviderConflict(t *testing.T) {
|
||||
api, _ := newOIDCTestAPI(t)
|
||||
values := url.Values{}
|
||||
values.Set("Action", actionCreateOpenIDConnectProvider)
|
||||
values.Set("Url", "https://accounts.google.com") // already mirrored from static config
|
||||
values.Set("ClientIDList.member.1", "x")
|
||||
|
||||
_, iamErr := api.ExecuteAction(context.Background(), values, true, "")
|
||||
if iamErr == nil {
|
||||
t.Fatal("expected conflict for duplicate provider")
|
||||
}
|
||||
if iamErr.Code != "EntityAlreadyExists" {
|
||||
t.Fatalf("expected EntityAlreadyExists, got %s", iamErr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteOpenIDConnectProvider(t *testing.T) {
|
||||
api, _ := newOIDCTestAPI(t)
|
||||
arn := "arn:aws:iam::111122223333:oidc-provider/accounts.google.com"
|
||||
|
||||
values := url.Values{}
|
||||
values.Set("Action", actionDeleteOpenIDConnectProvider)
|
||||
values.Set("OpenIDConnectProviderArn", arn)
|
||||
|
||||
if _, iamErr := api.ExecuteAction(context.Background(), values, true, ""); iamErr != nil {
|
||||
t.Fatalf("delete: %v", iamErr.Error)
|
||||
}
|
||||
// Verify gone.
|
||||
getValues := url.Values{}
|
||||
getValues.Set("Action", actionGetOpenIDConnectProvider)
|
||||
getValues.Set("OpenIDConnectProviderArn", arn)
|
||||
if _, iamErr := api.ExecuteAction(context.Background(), getValues, true, ""); iamErr == nil {
|
||||
t.Fatal("expected not-found after delete")
|
||||
}
|
||||
// Idempotent.
|
||||
if _, iamErr := api.ExecuteAction(context.Background(), values, true, ""); iamErr != nil {
|
||||
t.Fatalf("idempotent delete failed: %v", iamErr.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddRemoveClientID(t *testing.T) {
|
||||
api, _ := newOIDCTestAPI(t)
|
||||
arn := "arn:aws:iam::111122223333:oidc-provider/accounts.google.com"
|
||||
|
||||
add := url.Values{}
|
||||
add.Set("Action", actionAddClientIDToOpenIDConnectProvider)
|
||||
add.Set("OpenIDConnectProviderArn", arn)
|
||||
add.Set("ClientID", "extra-client")
|
||||
if _, iamErr := api.ExecuteAction(context.Background(), add, true, ""); iamErr != nil {
|
||||
t.Fatalf("add: %v", iamErr.Error)
|
||||
}
|
||||
|
||||
getValues := url.Values{}
|
||||
getValues.Set("Action", actionGetOpenIDConnectProvider)
|
||||
getValues.Set("OpenIDConnectProviderArn", arn)
|
||||
resp, iamErr := api.ExecuteAction(context.Background(), getValues, true, "")
|
||||
if iamErr != nil {
|
||||
t.Fatalf("get: %v", iamErr.Error)
|
||||
}
|
||||
got := resp.(*iamlib.GetOpenIDConnectProviderResponse).GetOpenIDConnectProviderResult.ClientIDList
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("expected 2 clients after add, got %v", got)
|
||||
}
|
||||
|
||||
// Idempotent add.
|
||||
if _, iamErr := api.ExecuteAction(context.Background(), add, true, ""); iamErr != nil {
|
||||
t.Fatalf("idempotent add: %v", iamErr.Error)
|
||||
}
|
||||
|
||||
// Remove.
|
||||
rm := url.Values{}
|
||||
rm.Set("Action", actionRemoveClientIDFromOpenIDConnectProvider)
|
||||
rm.Set("OpenIDConnectProviderArn", arn)
|
||||
rm.Set("ClientID", "extra-client")
|
||||
if _, iamErr := api.ExecuteAction(context.Background(), rm, true, ""); iamErr != nil {
|
||||
t.Fatalf("remove: %v", iamErr.Error)
|
||||
}
|
||||
resp, _ = api.ExecuteAction(context.Background(), getValues, true, "")
|
||||
got = resp.(*iamlib.GetOpenIDConnectProviderResponse).GetOpenIDConnectProviderResult.ClientIDList
|
||||
if len(got) != 1 || got[0] != "client-google" {
|
||||
t.Fatalf("unexpected clients after remove: %v", got)
|
||||
}
|
||||
|
||||
// Removing a missing client is a no-op.
|
||||
if _, iamErr := api.ExecuteAction(context.Background(), rm, true, ""); iamErr != nil {
|
||||
t.Fatalf("idempotent remove: %v", iamErr.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateThumbprintAndTags(t *testing.T) {
|
||||
api, _ := newOIDCTestAPI(t)
|
||||
arn := "arn:aws:iam::111122223333:oidc-provider/accounts.google.com"
|
||||
|
||||
upd := url.Values{}
|
||||
upd.Set("Action", actionUpdateOpenIDConnectProviderThumbprint)
|
||||
upd.Set("OpenIDConnectProviderArn", arn)
|
||||
upd.Set("ThumbprintList.member.1", "0000000000000000000000000000000000000000")
|
||||
upd.Set("ThumbprintList.member.2", "1111111111111111111111111111111111111111")
|
||||
if _, iamErr := api.ExecuteAction(context.Background(), upd, true, ""); iamErr != nil {
|
||||
t.Fatalf("update thumbprints: %v", iamErr.Error)
|
||||
}
|
||||
|
||||
tag := url.Values{}
|
||||
tag.Set("Action", actionTagOpenIDConnectProvider)
|
||||
tag.Set("OpenIDConnectProviderArn", arn)
|
||||
tag.Set("Tags.member.1.Key", "owner")
|
||||
tag.Set("Tags.member.1.Value", "platform")
|
||||
if _, iamErr := api.ExecuteAction(context.Background(), tag, true, ""); iamErr != nil {
|
||||
t.Fatalf("tag: %v", iamErr.Error)
|
||||
}
|
||||
|
||||
get := url.Values{}
|
||||
get.Set("Action", actionGetOpenIDConnectProvider)
|
||||
get.Set("OpenIDConnectProviderArn", arn)
|
||||
resp, iamErr := api.ExecuteAction(context.Background(), get, true, "")
|
||||
if iamErr != nil {
|
||||
t.Fatalf("get: %v", iamErr.Error)
|
||||
}
|
||||
gr := resp.(*iamlib.GetOpenIDConnectProviderResponse).GetOpenIDConnectProviderResult
|
||||
if len(gr.ThumbprintList) != 2 {
|
||||
t.Fatalf("ThumbprintList persisted incorrectly: %v", gr.ThumbprintList)
|
||||
}
|
||||
if len(gr.Tags) != 1 || gr.Tags[0].Key != "owner" {
|
||||
t.Fatalf("Tags persisted incorrectly: %v", gr.Tags)
|
||||
}
|
||||
|
||||
untag := url.Values{}
|
||||
untag.Set("Action", actionUntagOpenIDConnectProvider)
|
||||
untag.Set("OpenIDConnectProviderArn", arn)
|
||||
untag.Set("TagKeys.member.1", "owner")
|
||||
if _, iamErr := api.ExecuteAction(context.Background(), untag, true, ""); iamErr != nil {
|
||||
t.Fatalf("untag: %v", iamErr.Error)
|
||||
}
|
||||
resp, _ = api.ExecuteAction(context.Background(), get, true, "")
|
||||
gr = resp.(*iamlib.GetOpenIDConnectProviderResponse).GetOpenIDConnectProviderResult
|
||||
if len(gr.Tags) != 0 {
|
||||
t.Fatalf("Tags should be empty after untag, got: %v", gr.Tags)
|
||||
}
|
||||
}
|
||||
@@ -373,6 +373,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
filer.IamConfigDirectory + "/policies",
|
||||
filer.IamConfigDirectory + "/service_accounts",
|
||||
filer.IamConfigDirectory + "/groups",
|
||||
filer.IamConfigDirectory + "/oidc-providers",
|
||||
})
|
||||
|
||||
// Start bucket size metrics collection in background
|
||||
|
||||
+97
-24
@@ -53,6 +53,34 @@ const (
|
||||
// federationNameRegex validates the Name parameter for GetFederationToken per AWS spec
|
||||
var federationNameRegex = regexp.MustCompile(`^[\w+=,.@-]+$`)
|
||||
|
||||
// roleSessionNameRegex validates RoleSessionName per AWS spec.
|
||||
// Same character class as federation Name, but the length bounds differ
|
||||
// (RoleSessionName is 2..64).
|
||||
var roleSessionNameRegex = regexp.MustCompile(`^[\w+=,.@-]+$`)
|
||||
|
||||
const (
|
||||
minRoleSessionNameLen = 2
|
||||
maxRoleSessionNameLen = 64
|
||||
)
|
||||
|
||||
// validateRoleSessionName enforces the AWS RoleSessionName contract:
|
||||
// length 2..64, characters [\w+=,.@-]+. Returns the STS error code and a
|
||||
// descriptive error suitable for callers to surface to the caller.
|
||||
func validateRoleSessionName(name string) (STSErrorCode, error) {
|
||||
if name == "" {
|
||||
return STSErrMissingParameter, fmt.Errorf("RoleSessionName is required")
|
||||
}
|
||||
if len(name) < minRoleSessionNameLen || len(name) > maxRoleSessionNameLen {
|
||||
return STSErrInvalidParameterValue,
|
||||
fmt.Errorf("RoleSessionName must be between %d and %d characters", minRoleSessionNameLen, maxRoleSessionNameLen)
|
||||
}
|
||||
if !roleSessionNameRegex.MatchString(name) {
|
||||
return STSErrInvalidParameterValue,
|
||||
fmt.Errorf(`RoleSessionName contains invalid characters; allowed: [\w+=,.@-]`)
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// STS duration constants (AWS specification)
|
||||
const (
|
||||
minDurationSeconds = int64(900) // 15 minutes
|
||||
@@ -61,6 +89,27 @@ const (
|
||||
maxFederationDurationSeconds = int64(129600) // 36 hours (GetFederationToken max)
|
||||
)
|
||||
|
||||
// AWS limits inline session policies to 2048 characters for AssumeRole,
|
||||
// AssumeRoleWithWebIdentity, and AssumeRoleWithSAML. PackedPolicySize is
|
||||
// returned as a percentage of that budget so callers can detect how close
|
||||
// they are to the limit.
|
||||
const sessionPolicyBudgetBytes = 2048
|
||||
|
||||
// computePackedPolicySize returns the inline session policy size as a
|
||||
// percentage of the per-action budget, or nil when no session policy was
|
||||
// provided. Output is bounded to [0, 100] for AWS-compat reporting; the
|
||||
// actual policy size validation happens upstream in NormalizeSessionPolicy.
|
||||
func computePackedPolicySize(policyJSON string) *int64 {
|
||||
if policyJSON == "" {
|
||||
return nil
|
||||
}
|
||||
pct := int64(len(policyJSON)) * 100 / sessionPolicyBudgetBytes
|
||||
if pct > 100 {
|
||||
pct = 100
|
||||
}
|
||||
return &pct
|
||||
}
|
||||
|
||||
// parseDurationSecondsWithBounds parses and validates the DurationSeconds parameter
|
||||
// against the given min and max bounds. Returns nil if the parameter is not provided.
|
||||
func parseDurationSecondsWithBounds(r *http.Request, minSec, maxSec int64) (*int64, STSErrorCode, error) {
|
||||
@@ -112,6 +161,22 @@ func (h *STSHandlers) getAccountID() string {
|
||||
return defaultAccountID
|
||||
}
|
||||
|
||||
// assumeRoleWithWebIdentity dispatches the request through the IAMManager
|
||||
// wrapper when one is wired so its cross-account provider scope check and
|
||||
// per-role MaxSessionDuration clamp run for the public AWS-SDK path. Without
|
||||
// this dispatch, both checks are silently skipped because they live on the
|
||||
// IAMManager, not on the bare STS service.
|
||||
func (h *STSHandlers) assumeRoleWithWebIdentity(ctx context.Context, request *sts.AssumeRoleWithWebIdentityRequest) (*sts.AssumeRoleResponse, error) {
|
||||
if h.iam != nil && h.iam.iamIntegration != nil {
|
||||
if provider, ok := h.iam.iamIntegration.(IAMManagerProvider); ok {
|
||||
if mgr := provider.GetIAMManager(); mgr != nil {
|
||||
return mgr.AssumeRoleWithWebIdentity(ctx, request)
|
||||
}
|
||||
}
|
||||
}
|
||||
return h.stsService.AssumeRoleWithWebIdentity(ctx, request)
|
||||
}
|
||||
|
||||
// HandleSTSRequest is the main entry point for STS requests
|
||||
// It routes requests based on the Action parameter
|
||||
func (h *STSHandlers) HandleSTSRequest(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -164,15 +229,16 @@ func (h *STSHandlers) handleAssumeRoleWithWebIdentity(w http.ResponseWriter, r *
|
||||
return
|
||||
}
|
||||
|
||||
if roleArn == "" {
|
||||
h.writeSTSErrorResponse(w, r, STSErrMissingParameter,
|
||||
fmt.Errorf("RoleArn is required"))
|
||||
return
|
||||
}
|
||||
// RoleArn is intentionally optional here: claim-based policy mode
|
||||
// (Phase 3b) advertises that callers MAY omit RoleArn so the STS
|
||||
// service derives the assumed-role ARN from the configured policy
|
||||
// claim. The bare-STS path validates this — when the IDP isn't
|
||||
// configured for claim-based mode (or fails to emit policies) it
|
||||
// returns a precise error that this handler maps to the right STS
|
||||
// error code below.
|
||||
|
||||
if roleSessionName == "" {
|
||||
h.writeSTSErrorResponse(w, r, STSErrMissingParameter,
|
||||
fmt.Errorf("RoleSessionName is required"))
|
||||
if errCode, err := validateRoleSessionName(roleSessionName); err != nil {
|
||||
h.writeSTSErrorResponse(w, r, errCode, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -211,8 +277,11 @@ func (h *STSHandlers) handleAssumeRoleWithWebIdentity(w http.ResponseWriter, r *
|
||||
Policy: sessionPolicyPtr,
|
||||
}
|
||||
|
||||
// Call STS service
|
||||
response, err := h.stsService.AssumeRoleWithWebIdentity(ctx, request)
|
||||
// Prefer the IAMManager wrapper so the cross-account provider scope
|
||||
// (enforceProviderAccountScope) and per-role MaxSessionDuration clamp
|
||||
// run for SDK callers too. Falling back to the bare STS service keeps
|
||||
// embedded test setups (no IAM integration wired) working.
|
||||
response, err := h.assumeRoleWithWebIdentity(ctx, request)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("AssumeRoleWithWebIdentity failed: %v", err)
|
||||
|
||||
@@ -245,6 +314,7 @@ func (h *STSHandlers) handleAssumeRoleWithWebIdentity(w http.ResponseWriter, r *
|
||||
Expiration: response.Credentials.Expiration.Format(time.RFC3339),
|
||||
},
|
||||
SubjectFromWebIdentityToken: response.AssumedRoleUser.Subject,
|
||||
PackedPolicySize: computePackedPolicySize(sessionPolicyJSON),
|
||||
},
|
||||
}
|
||||
xmlResponse.ResponseMetadata.RequestId = request_id.GetFromRequest(r)
|
||||
@@ -264,9 +334,8 @@ func (h *STSHandlers) handleAssumeRole(w http.ResponseWriter, r *http.Request) {
|
||||
// Validate required parameters
|
||||
// RoleArn is optional to support S3-compatible clients that omit it
|
||||
|
||||
if roleSessionName == "" {
|
||||
h.writeSTSErrorResponse(w, r, STSErrMissingParameter,
|
||||
fmt.Errorf("RoleSessionName is required"))
|
||||
if errCode, err := validateRoleSessionName(roleSessionName); err != nil {
|
||||
h.writeSTSErrorResponse(w, r, errCode, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -373,8 +442,9 @@ func (h *STSHandlers) handleAssumeRole(w http.ResponseWriter, r *http.Request) {
|
||||
// Build and return response
|
||||
xmlResponse := &AssumeRoleResponse{
|
||||
Result: AssumeRoleResult{
|
||||
Credentials: stsCreds,
|
||||
AssumedRoleUser: assumedUser,
|
||||
Credentials: stsCreds,
|
||||
AssumedRoleUser: assumedUser,
|
||||
PackedPolicySize: computePackedPolicySize(sessionPolicyJSON),
|
||||
},
|
||||
}
|
||||
xmlResponse.ResponseMetadata.RequestId = request_id.GetFromRequest(r)
|
||||
@@ -397,9 +467,8 @@ func (h *STSHandlers) handleAssumeRoleWithLDAPIdentity(w http.ResponseWriter, r
|
||||
return
|
||||
}
|
||||
|
||||
if roleSessionName == "" {
|
||||
h.writeSTSErrorResponse(w, r, STSErrMissingParameter,
|
||||
fmt.Errorf("RoleSessionName is required"))
|
||||
if errCode, err := validateRoleSessionName(roleSessionName); err != nil {
|
||||
h.writeSTSErrorResponse(w, r, errCode, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -514,8 +583,9 @@ func (h *STSHandlers) handleAssumeRoleWithLDAPIdentity(w http.ResponseWriter, r
|
||||
// Build and return response
|
||||
xmlResponse := &AssumeRoleWithLDAPIdentityResponse{
|
||||
Result: LDAPIdentityResult{
|
||||
Credentials: stsCreds,
|
||||
AssumedRoleUser: assumedUser,
|
||||
Credentials: stsCreds,
|
||||
AssumedRoleUser: assumedUser,
|
||||
PackedPolicySize: computePackedPolicySize(sessionPolicyJSON),
|
||||
},
|
||||
}
|
||||
xmlResponse.ResponseMetadata.RequestId = request_id.GetFromRequest(r)
|
||||
@@ -906,6 +976,7 @@ type WebIdentityResult struct {
|
||||
Credentials STSCredentials `xml:"Credentials"`
|
||||
SubjectFromWebIdentityToken string `xml:"SubjectFromWebIdentityToken,omitempty"`
|
||||
AssumedRoleUser *AssumedRoleUser `xml:"AssumedRoleUser,omitempty"`
|
||||
PackedPolicySize *int64 `xml:"PackedPolicySize,omitempty"`
|
||||
}
|
||||
|
||||
// STSCredentials represents temporary security credentials
|
||||
@@ -933,8 +1004,9 @@ type AssumeRoleResponse struct {
|
||||
|
||||
// AssumeRoleResult contains the result of AssumeRole
|
||||
type AssumeRoleResult struct {
|
||||
Credentials STSCredentials `xml:"Credentials"`
|
||||
AssumedRoleUser *AssumedRoleUser `xml:"AssumedRoleUser,omitempty"`
|
||||
Credentials STSCredentials `xml:"Credentials"`
|
||||
AssumedRoleUser *AssumedRoleUser `xml:"AssumedRoleUser,omitempty"`
|
||||
PackedPolicySize *int64 `xml:"PackedPolicySize,omitempty"`
|
||||
}
|
||||
|
||||
// AssumeRoleWithLDAPIdentityResponse is the response for AssumeRoleWithLDAPIdentity
|
||||
@@ -948,8 +1020,9 @@ type AssumeRoleWithLDAPIdentityResponse struct {
|
||||
|
||||
// LDAPIdentityResult contains the result of AssumeRoleWithLDAPIdentity
|
||||
type LDAPIdentityResult struct {
|
||||
Credentials STSCredentials `xml:"Credentials"`
|
||||
AssumedRoleUser *AssumedRoleUser `xml:"AssumedRoleUser,omitempty"`
|
||||
Credentials STSCredentials `xml:"Credentials"`
|
||||
AssumedRoleUser *AssumedRoleUser `xml:"AssumedRoleUser,omitempty"`
|
||||
PackedPolicySize *int64 `xml:"PackedPolicySize,omitempty"`
|
||||
}
|
||||
|
||||
// GetCallerIdentityResponse is the response for GetCallerIdentity
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
)
|
||||
|
||||
// TestAssumeRoleWithWebIdentity_DispatchesThroughIAMManager confirms the
|
||||
// public STS HTTP path goes through IAMManager.AssumeRoleWithWebIdentity (and
|
||||
// thereby its enforceProviderAccountScope check and MaxSessionDuration
|
||||
// clamp) instead of bypassing to the bare STS service. The two paths surface
|
||||
// different errors when their underlying service is uninitialized, which is
|
||||
// the cheapest behavioural signal that doesn't require a full OIDC stack.
|
||||
func TestAssumeRoleWithWebIdentity_DispatchesThroughIAMManager(t *testing.T) {
|
||||
req := &sts.AssumeRoleWithWebIdentityRequest{
|
||||
RoleArn: "arn:aws:iam::111111111111:role/Test",
|
||||
WebIdentityToken: "ignored",
|
||||
RoleSessionName: "session",
|
||||
}
|
||||
|
||||
t.Run("with IAMManager wired", func(t *testing.T) {
|
||||
mgr := integration.NewIAMManager() // not initialized on purpose
|
||||
h := &STSHandlers{
|
||||
stsService: nil, // intentionally nil; the wrapper must run first
|
||||
iam: &IdentityAccessManagement{
|
||||
iamIntegration: NewS3IAMIntegration(mgr, ""),
|
||||
},
|
||||
}
|
||||
_, err := h.assumeRoleWithWebIdentity(context.Background(), req)
|
||||
if err == nil || !strings.Contains(err.Error(), "IAM manager not initialized") {
|
||||
t.Fatalf("expected IAMManager wrapper to handle the call; got err=%v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("without IAM integration", func(t *testing.T) {
|
||||
h := &STSHandlers{
|
||||
stsService: sts.NewSTSService(), // not initialized
|
||||
iam: &IdentityAccessManagement{},
|
||||
}
|
||||
_, err := h.assumeRoleWithWebIdentity(context.Background(), req)
|
||||
if err == nil || !strings.Contains(err.Error(), "STS service not initialized") {
|
||||
t.Fatalf("expected fallback to bare STS service; got err=%v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestAssumeRoleWithWebIdentity_AllowsEmptyRoleArn confirms the HTTP handler
|
||||
// no longer rejects empty RoleArn before STS sees the request. Phase 3b's
|
||||
// claim-based mode advertises that callers MAY omit RoleArn so the policy
|
||||
// claim derives the assumed-role ARN; the handler must let that flow
|
||||
// through. STS-layer failures (invalid token, claim-mode not configured) are
|
||||
// surfaced separately and don't read "RoleArn is required".
|
||||
func TestAssumeRoleWithWebIdentity_AllowsEmptyRoleArn(t *testing.T) {
|
||||
stsService, _ := setupTestSTSService(t)
|
||||
h := &STSHandlers{
|
||||
stsService: stsService,
|
||||
iam: &IdentityAccessManagement{},
|
||||
}
|
||||
|
||||
form := url.Values{}
|
||||
form.Set("Action", "AssumeRoleWithWebIdentity")
|
||||
form.Set("WebIdentityToken", "not-a-real-jwt")
|
||||
form.Set("RoleSessionName", "session-1")
|
||||
// RoleArn intentionally omitted.
|
||||
|
||||
req := httptest.NewRequest("POST", "/", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
if err := req.ParseForm(); err != nil {
|
||||
t.Fatalf("ParseForm: %v", err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
h.handleAssumeRoleWithWebIdentity(rr, req)
|
||||
|
||||
body := rr.Body.String()
|
||||
if strings.Contains(body, "RoleArn is required") {
|
||||
t.Fatalf("HTTP handler rejected empty RoleArn pre-STS; body=%q", body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package s3api
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestComputePackedPolicySize(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
policyLen int
|
||||
empty bool
|
||||
want int64
|
||||
}{
|
||||
{"empty -> nil", 0, true, 0},
|
||||
{"tiny policy -> 0%", 10, false, 0},
|
||||
{"half budget -> 50%", sessionPolicyBudgetBytes / 2, false, 50},
|
||||
{"full budget -> 100%", sessionPolicyBudgetBytes, false, 100},
|
||||
{"oversized -> capped at 100", sessionPolicyBudgetBytes * 3, false, 100},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
policy := repeat('a', tc.policyLen)
|
||||
got := computePackedPolicySize(policy)
|
||||
switch {
|
||||
case tc.empty:
|
||||
if got != nil {
|
||||
t.Fatalf("expected nil for empty input, got %d", *got)
|
||||
}
|
||||
case got == nil:
|
||||
t.Fatalf("expected non-nil result, got nil")
|
||||
case *got != tc.want:
|
||||
t.Fatalf("got=%d want=%d", *got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package s3api
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidateRoleSessionName(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
input string
|
||||
wantErr bool
|
||||
// wantCode is checked only when wantErr is true
|
||||
wantCode STSErrorCode
|
||||
}{
|
||||
{"empty rejected", "", true, STSErrMissingParameter},
|
||||
{"single char rejected (below min len 2)", "a", true, STSErrInvalidParameterValue},
|
||||
{"min length 2 accepted", "ab", false, ""},
|
||||
{"plain ascii accepted", "session-name_1", false, ""},
|
||||
{"all special chars allowed", "+=,.@-", false, ""},
|
||||
{"email-style accepted", "alice@example.com", false, ""},
|
||||
{"max length 64 accepted", string(make([]byte, 64)), true, STSErrInvalidParameterValue}, // zero bytes -> invalid charset
|
||||
{"max length 64 valid charset accepted", repeat('a', 64), false, ""},
|
||||
{"length 65 rejected", repeat('a', 65), true, STSErrInvalidParameterValue},
|
||||
{"space rejected", "alice bob", true, STSErrInvalidParameterValue},
|
||||
{"slash rejected", "alice/bob", true, STSErrInvalidParameterValue},
|
||||
{"colon rejected", "alice:bob", true, STSErrInvalidParameterValue},
|
||||
{"unicode rejected", "alicé", true, STSErrInvalidParameterValue},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
code, err := validateRoleSessionName(tc.input)
|
||||
gotErr := err != nil
|
||||
if gotErr != tc.wantErr {
|
||||
t.Fatalf("err mismatch: got=%v want=%v (err=%v)", gotErr, tc.wantErr, err)
|
||||
}
|
||||
if tc.wantErr && code != tc.wantCode {
|
||||
t.Fatalf("code mismatch: got=%s want=%s", code, tc.wantCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func repeat(b byte, n int) string {
|
||||
out := make([]byte, n)
|
||||
for i := range out {
|
||||
out[i] = b
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
+18
-14
@@ -98,31 +98,35 @@ func GetActualRemoteHost(r *http.Request) string {
|
||||
}
|
||||
|
||||
func (g *Guard) checkWhiteList(w http.ResponseWriter, r *http.Request) error {
|
||||
if g.isEmptyWhiteList {
|
||||
return nil
|
||||
}
|
||||
|
||||
host := GetActualRemoteHost(r)
|
||||
|
||||
// Check exact match first (works for both IPs and hostnames)
|
||||
if _, ok := g.whiteListIp[host]; ok {
|
||||
if g.IsWhiteListed(host) {
|
||||
return nil
|
||||
}
|
||||
glog.V(0).Infof("Not in whitelist: %s (original RemoteAddr: %s)", host, r.RemoteAddr)
|
||||
return fmt.Errorf("Not in whitelist: %s", host)
|
||||
}
|
||||
|
||||
// Check CIDR ranges (only for valid IP addresses)
|
||||
// IsWhiteListed returns true if the given host IP is allowed by the guard.
|
||||
// When no whitelist is configured (security inactive), all hosts are allowed.
|
||||
func (g *Guard) IsWhiteListed(host string) bool {
|
||||
if !g.isWriteActive {
|
||||
return true
|
||||
}
|
||||
if g.isEmptyWhiteList {
|
||||
return true
|
||||
}
|
||||
if _, ok := g.whiteListIp[host]; ok {
|
||||
return true
|
||||
}
|
||||
remote := net.ParseIP(host)
|
||||
if remote != nil {
|
||||
for _, cidrnet := range g.whiteListCIDR {
|
||||
// If the whitelist entry contains a "/" it
|
||||
// is a CIDR range, and we should check the
|
||||
if cidrnet.Contains(remote) {
|
||||
return nil
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
glog.V(0).Infof("Not in whitelist: %s (original RemoteAddr: %s)", host, r.RemoteAddr)
|
||||
return fmt.Errorf("Not in whitelist: %s", host)
|
||||
return false
|
||||
}
|
||||
|
||||
func (g *Guard) UpdateWhiteList(whiteList []string) {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package security
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestIsWhiteListedEmptyConfigAllowsEverything pins the contract that the
|
||||
// gRPC admin auth helper relies on: when no whitelist and no signing key
|
||||
// are configured, IsWhiteListed accepts any host (including the empty
|
||||
// string and unparseable peer addresses like the gRPC "@" passthrough
|
||||
// form). Otherwise insecure default deployments would lock themselves out
|
||||
// of every destructive admin RPC.
|
||||
func TestIsWhiteListedEmptyConfigAllowsEverything(t *testing.T) {
|
||||
g := NewGuard(nil, "", 0, "", 0)
|
||||
for _, host := range []string{"", "@", "127.0.0.1", "::1", "garbage:value"} {
|
||||
if !g.IsWhiteListed(host) {
|
||||
t.Errorf("empty config should accept host=%q, got false", host)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsWhiteListedWithListRejectsUnknown(t *testing.T) {
|
||||
g := NewGuard([]string{"10.0.0.1", "192.168.1.0/24"}, "", 0, "", 0)
|
||||
cases := []struct {
|
||||
host string
|
||||
want bool
|
||||
}{
|
||||
{"10.0.0.1", true},
|
||||
{"192.168.1.42", true},
|
||||
{"192.168.2.1", false},
|
||||
{"127.0.0.1", false},
|
||||
{"", false},
|
||||
{"@", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := g.IsWhiteListed(tc.host); got != tc.want {
|
||||
t.Errorf("IsWhiteListed(%q) = %v want %v", tc.host, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsWhiteListedWithSigningKeyButNoWhitelistAllowsAll(t *testing.T) {
|
||||
// JWT-only mode: signing key set, whitelist empty. Without this branch
|
||||
// the gRPC admin auth helper would falsely deny in-process callers when
|
||||
// the operator wires up signing keys but hasn't enumerated IPs.
|
||||
g := NewGuard(nil, "deadbeef", 0, "", 0)
|
||||
for _, host := range []string{"", "@", "127.0.0.1"} {
|
||||
if !g.IsWhiteListed(host) {
|
||||
t.Errorf("signing-key + empty whitelist should accept host=%q", host)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,14 @@ package weed_server
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/peer"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/version"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
@@ -22,10 +27,53 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
// checkGrpcAdminAuth verifies the gRPC caller is authorized for destructive
|
||||
// admin operations by checking the peer address against the guard's whitelist.
|
||||
//
|
||||
// IP extraction prefers a typed *net.TCPAddr where available, falling back to
|
||||
// SplitHostPort on the string form, then to the raw string. The fallback
|
||||
// chain matters because in-process/passthrough connections used in tests
|
||||
// surface as unparseable strings like "@"; with an empty whitelist the
|
||||
// allow-all branch in IsWhiteListed accepts them, with a whitelist they're
|
||||
// denied as expected.
|
||||
//
|
||||
// Failed authorization attempts are logged so an operator running with a
|
||||
// configured whitelist can spot misconfigured callers and probe attempts.
|
||||
func (vs *VolumeServer) checkGrpcAdminAuth(ctx context.Context) error {
|
||||
if vs.guard == nil {
|
||||
return nil
|
||||
}
|
||||
pr, ok := peer.FromContext(ctx)
|
||||
if !ok {
|
||||
// Real gRPC connections always populate peer info; if we don't know
|
||||
// who the caller is, deny.
|
||||
glog.V(0).Infof("gRPC admin auth failed: no peer info")
|
||||
return status.Error(codes.PermissionDenied, "no peer info")
|
||||
}
|
||||
addr := pr.Addr.String()
|
||||
var host string
|
||||
if tcpAddr, ok := pr.Addr.(*net.TCPAddr); ok {
|
||||
host = tcpAddr.IP.String()
|
||||
} else if h, _, splitErr := net.SplitHostPort(addr); splitErr == nil {
|
||||
host = h
|
||||
} else {
|
||||
host = addr
|
||||
}
|
||||
if !vs.guard.IsWhiteListed(host) {
|
||||
glog.V(0).Infof("gRPC admin auth failed: %s is not whitelisted (remote: %s)", host, addr)
|
||||
return status.Errorf(codes.PermissionDenied, "not authorized: %s", host)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) DeleteCollection(ctx context.Context, req *volume_server_pb.DeleteCollectionRequest) (*volume_server_pb.DeleteCollectionResponse, error) {
|
||||
|
||||
resp := &volume_server_pb.DeleteCollectionResponse{}
|
||||
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
err := vs.store.DeleteCollection(req.Collection)
|
||||
|
||||
if err != nil {
|
||||
@@ -41,6 +89,10 @@ func (vs *VolumeServer) DeleteCollection(ctx context.Context, req *volume_server
|
||||
func (vs *VolumeServer) AllocateVolume(ctx context.Context, req *volume_server_pb.AllocateVolumeRequest) (*volume_server_pb.AllocateVolumeResponse, error) {
|
||||
resp := &volume_server_pb.AllocateVolumeResponse{}
|
||||
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if err := vs.CheckMaintenanceMode(); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
@@ -72,6 +124,10 @@ func (vs *VolumeServer) VolumeMount(ctx context.Context, req *volume_server_pb.V
|
||||
|
||||
resp := &volume_server_pb.VolumeMountResponse{}
|
||||
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
err := vs.store.MountVolume(needle.VolumeId(req.VolumeId))
|
||||
|
||||
if err != nil {
|
||||
@@ -88,6 +144,10 @@ func (vs *VolumeServer) VolumeUnmount(ctx context.Context, req *volume_server_pb
|
||||
|
||||
resp := &volume_server_pb.VolumeUnmountResponse{}
|
||||
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
err := vs.store.UnmountVolume(needle.VolumeId(req.VolumeId))
|
||||
|
||||
if err != nil {
|
||||
@@ -103,11 +163,15 @@ func (vs *VolumeServer) VolumeUnmount(ctx context.Context, req *volume_server_pb
|
||||
func (vs *VolumeServer) VolumeDelete(ctx context.Context, req *volume_server_pb.VolumeDeleteRequest) (*volume_server_pb.VolumeDeleteResponse, error) {
|
||||
resp := &volume_server_pb.VolumeDeleteResponse{}
|
||||
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if err := vs.CheckMaintenanceMode(); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
err := vs.store.DeleteVolume(needle.VolumeId(req.VolumeId), req.OnlyEmpty)
|
||||
err := vs.store.DeleteVolume(needle.VolumeId(req.VolumeId), req.OnlyEmpty, req.KeepRemoteData)
|
||||
|
||||
if err != nil {
|
||||
glog.Errorf("volume delete %v: %v", req, err)
|
||||
@@ -122,6 +186,10 @@ func (vs *VolumeServer) VolumeDelete(ctx context.Context, req *volume_server_pb.
|
||||
func (vs *VolumeServer) VolumeConfigure(ctx context.Context, req *volume_server_pb.VolumeConfigureRequest) (*volume_server_pb.VolumeConfigureResponse, error) {
|
||||
resp := &volume_server_pb.VolumeConfigureResponse{}
|
||||
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if err := vs.CheckMaintenanceMode(); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
@@ -236,6 +304,10 @@ func (vs *VolumeServer) notifyMasterVolumeReadonly(ctx context.Context, v *stora
|
||||
func (vs *VolumeServer) VolumeMarkReadonly(ctx context.Context, req *volume_server_pb.VolumeMarkReadonlyRequest) (*volume_server_pb.VolumeMarkReadonlyResponse, error) {
|
||||
resp := &volume_server_pb.VolumeMarkReadonlyResponse{}
|
||||
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
v := vs.store.GetVolume(needle.VolumeId(req.VolumeId))
|
||||
if v == nil {
|
||||
return resp, fmt.Errorf("volume %d not found", req.VolumeId)
|
||||
@@ -251,6 +323,10 @@ func (vs *VolumeServer) VolumeMarkReadonly(ctx context.Context, req *volume_serv
|
||||
func (vs *VolumeServer) VolumeMarkWritable(ctx context.Context, req *volume_server_pb.VolumeMarkWritableRequest) (*volume_server_pb.VolumeMarkWritableResponse, error) {
|
||||
resp := &volume_server_pb.VolumeMarkWritableResponse{}
|
||||
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
v := vs.store.GetVolume(needle.VolumeId(req.VolumeId))
|
||||
if v == nil {
|
||||
return resp, fmt.Errorf("volume %d not found", req.VolumeId)
|
||||
@@ -308,6 +384,10 @@ func (vs *VolumeServer) VolumeServerLeave(ctx context.Context, req *volume_serve
|
||||
|
||||
resp := &volume_server_pb.VolumeServerLeaveResponse{}
|
||||
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
vs.StopHeartbeat()
|
||||
|
||||
return resp, nil
|
||||
|
||||
@@ -36,7 +36,9 @@ func (vs *VolumeServer) VolumeCopy(req *volume_server_pb.VolumeCopyRequest, stre
|
||||
|
||||
glog.V(0).Infof("volume %d already exists. deleted before copying...", req.VolumeId)
|
||||
|
||||
err := vs.store.DeleteVolume(needle.VolumeId(req.VolumeId), false)
|
||||
// keep remote data: the inbound copy carries a .vif that may point at
|
||||
// the same cloud-tier object the existing volume references.
|
||||
err := vs.store.DeleteVolume(needle.VolumeId(req.VolumeId), false, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to delete existing volume %d: %v", req.VolumeId, err)
|
||||
}
|
||||
|
||||
@@ -316,6 +316,9 @@ func (vs *VolumeServer) VolumeEcShardsCopy(ctx context.Context, req *volume_serv
|
||||
// VolumeEcShardsDelete local delete the .ecx and some ec data slices if not needed
|
||||
// the shard should not be mounted before calling this.
|
||||
func (vs *VolumeServer) VolumeEcShardsDelete(ctx context.Context, req *volume_server_pb.VolumeEcShardsDeleteRequest) (*volume_server_pb.VolumeEcShardsDeleteResponse, error) {
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := vs.CheckMaintenanceMode(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ import (
|
||||
)
|
||||
|
||||
func (vs *VolumeServer) ScrubVolume(ctx context.Context, req *volume_server_pb.ScrubVolumeRequest) (*volume_server_pb.ScrubVolumeResponse, error) {
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vids := []needle.VolumeId{}
|
||||
if len(req.GetVolumeIds()) == 0 {
|
||||
for _, l := range vs.store.Locations {
|
||||
|
||||
@@ -34,6 +34,9 @@ func (vs *VolumeServer) VacuumVolumeCheck(ctx context.Context, req *volume_serve
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) VacuumVolumeCompact(req *volume_server_pb.VacuumVolumeCompactRequest, stream volume_server_pb.VolumeServer_VacuumVolumeCompactServer) error {
|
||||
if err := vs.checkGrpcAdminAuth(stream.Context()); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := vs.CheckMaintenanceMode(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -80,6 +83,9 @@ func (vs *VolumeServer) VacuumVolumeCompact(req *volume_server_pb.VacuumVolumeCo
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) VacuumVolumeCommit(ctx context.Context, req *volume_server_pb.VacuumVolumeCommitRequest) (*volume_server_pb.VacuumVolumeCommitResponse, error) {
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := vs.CheckMaintenanceMode(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -106,6 +112,9 @@ func (vs *VolumeServer) VacuumVolumeCommit(ctx context.Context, req *volume_serv
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) VacuumVolumeCleanup(ctx context.Context, req *volume_server_pb.VacuumVolumeCleanupRequest) (*volume_server_pb.VacuumVolumeCleanupResponse, error) {
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := vs.CheckMaintenanceMode(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -352,7 +352,7 @@ func doDeleteVolumesWithLocations(commandEnv *CommandEnv, volumeIds []needle.Vol
|
||||
|
||||
for _, l := range locations {
|
||||
ewg.Add(func() error {
|
||||
if err := deleteVolume(commandEnv.option.GrpcDialOption, vid, l.ServerAddress(), false); err != nil {
|
||||
if err := deleteVolume(commandEnv.option.GrpcDialOption, vid, l.ServerAddress(), false, false); err != nil {
|
||||
return fmt.Errorf("deleteVolume %s volume %d: %v", l.Url, vid, err)
|
||||
}
|
||||
fmt.Printf("deleted volume %d from %s\n", vid, l.Url)
|
||||
|
||||
@@ -50,6 +50,6 @@ func (c *commandVolumeDelete) Do(args []string, commandEnv *CommandEnv, writer i
|
||||
|
||||
volumeId := needle.VolumeId(*volumeIdInt)
|
||||
|
||||
return deleteVolume(commandEnv.option.GrpcDialOption, volumeId, sourceVolumeServer, false)
|
||||
return deleteVolume(commandEnv.option.GrpcDialOption, volumeId, sourceVolumeServer, false, false)
|
||||
|
||||
}
|
||||
@@ -71,7 +71,7 @@ func (c *commandVolumeDeleteEmpty) Do(args []string, commandEnv *CommandEnv, wri
|
||||
if *applyBalancing {
|
||||
log.Printf("deleting empty volume %d from %s", v.Id, dn.Id)
|
||||
if deleteErr := deleteVolume(commandEnv.option.GrpcDialOption, needle.VolumeId(v.Id),
|
||||
pb.NewServerAddressFromDataNode(dn), true); deleteErr != nil {
|
||||
pb.NewServerAddressFromDataNode(dn), true, false); deleteErr != nil {
|
||||
err = deleteErr
|
||||
}
|
||||
continue
|
||||
|
||||
@@ -312,8 +312,10 @@ func (c *commandVolumeFixReplication) deleteOneVolume(commandEnv *CommandEnv, wr
|
||||
}
|
||||
}
|
||||
|
||||
// Surplus replica being trimmed; keep the remote object since other
|
||||
// replicas of the same .vif still reference it.
|
||||
if err := deleteVolume(commandEnv.option.GrpcDialOption, needle.VolumeId(replica.info.Id),
|
||||
pb.NewServerAddressFromDataNode(replica.location.dataNode), false); err != nil {
|
||||
pb.NewServerAddressFromDataNode(replica.location.dataNode), false, true); err != nil {
|
||||
fmt.Fprintf(writer, "deleting volume %d from %s : %v", replica.info.Id, replica.location.dataNode.Id, err)
|
||||
}
|
||||
|
||||
|
||||
@@ -119,7 +119,7 @@ func (c *commandVolumeMerge) Do(args []string, commandEnv *CommandEnv, writer io
|
||||
if !cleanupTarget {
|
||||
return
|
||||
}
|
||||
if delErr := deleteVolume(commandEnv.option.GrpcDialOption, volumeId, targetServer, false); delErr != nil {
|
||||
if delErr := deleteVolume(commandEnv.option.GrpcDialOption, volumeId, targetServer, false, false); delErr != nil {
|
||||
glog.Warningf("failed to clean up temporary merge volume %d on %s: %v", volumeId, targetServer, delErr)
|
||||
}
|
||||
}()
|
||||
@@ -180,7 +180,7 @@ func (c *commandVolumeMerge) Do(args []string, commandEnv *CommandEnv, writer io
|
||||
}
|
||||
}
|
||||
|
||||
if err = deleteVolume(commandEnv.option.GrpcDialOption, volumeId, targetServer, false); err != nil {
|
||||
if err = deleteVolume(commandEnv.option.GrpcDialOption, volumeId, targetServer, false, false); err != nil {
|
||||
return err
|
||||
}
|
||||
cleanupTarget = false
|
||||
|
||||
@@ -105,7 +105,7 @@ func LiveMoveVolume(grpcDialOption grpc.DialOption, writer io.Writer, volumeId n
|
||||
}
|
||||
|
||||
log.Printf("deleting volume %d from %s", volumeId, sourceVolumeServer)
|
||||
if err = deleteVolume(grpcDialOption, volumeId, sourceVolumeServer, false); err != nil {
|
||||
if err = deleteVolume(grpcDialOption, volumeId, sourceVolumeServer, false, true); err != nil {
|
||||
return fmt.Errorf("delete volume %d from %s: %v", volumeId, sourceVolumeServer, err)
|
||||
}
|
||||
|
||||
@@ -202,11 +202,15 @@ func tailVolume(grpcDialOption grpc.DialOption, volumeId needle.VolumeId, source
|
||||
|
||||
}
|
||||
|
||||
func deleteVolume(grpcDialOption grpc.DialOption, volumeId needle.VolumeId, sourceVolumeServer pb.ServerAddress, onlyEmpty bool) (err error) {
|
||||
// deleteVolume removes the volume from sourceVolumeServer. When keepRemoteData
|
||||
// is true, the cloud-tier object backing the volume is left intact — used on
|
||||
// the source side of a move where another server is taking over the same .vif.
|
||||
func deleteVolume(grpcDialOption grpc.DialOption, volumeId needle.VolumeId, sourceVolumeServer pb.ServerAddress, onlyEmpty bool, keepRemoteData bool) (err error) {
|
||||
return operation.WithVolumeServerClient(false, sourceVolumeServer, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
_, deleteErr := volumeServerClient.VolumeDelete(context.Background(), &volume_server_pb.VolumeDeleteRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
OnlyEmpty: onlyEmpty,
|
||||
VolumeId: uint32(volumeId),
|
||||
OnlyEmpty: onlyEmpty,
|
||||
KeepRemoteData: keepRemoteData,
|
||||
})
|
||||
return deleteErr
|
||||
})
|
||||
|
||||
@@ -312,7 +312,7 @@ func (c *commandVolumeTierMove) doMoveOneVolume(commandEnv *CommandEnv, writer i
|
||||
if preserveServers[loc.Url] {
|
||||
continue
|
||||
}
|
||||
if err = deleteVolume(commandEnv.option.GrpcDialOption, vid, loc.ServerAddress(), false); err != nil {
|
||||
if err = deleteVolume(commandEnv.option.GrpcDialOption, vid, loc.ServerAddress(), false, false); err != nil {
|
||||
fmt.Fprintf(writer, "failed to delete volume %d on %s: %v\n", vid, loc.Url, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,7 +164,10 @@ func doVolumeTierUpload(commandEnv *CommandEnv, writer io.Writer, collection str
|
||||
continue
|
||||
}
|
||||
fmt.Printf("delete volume %d from Url:%s\n", vid, location.Url)
|
||||
err = deleteVolume(commandEnv.option.GrpcDialOption, vid, location.ServerAddress(), false)
|
||||
// Other replicas were never tier-uploaded; their .vif (if any) points
|
||||
// to the same cloud key just written for this volume. Keep the remote
|
||||
// object so the tier-uploaded replica still references valid data.
|
||||
err = deleteVolume(commandEnv.option.GrpcDialOption, vid, location.ServerAddress(), false, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("deleteVolume %s volume %d: %v", location.Url, vid, err)
|
||||
}
|
||||
|
||||
@@ -301,7 +301,7 @@ func (l *DiskLocation) DeleteCollectionFromDiskLocation(collection string) (e er
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
for k, v := range delVolsMap {
|
||||
if err := v.Destroy(false); err != nil {
|
||||
if err := v.Destroy(false, false); err != nil {
|
||||
errChain <- err
|
||||
} else {
|
||||
l.volumesLock.Lock()
|
||||
@@ -336,12 +336,12 @@ func (l *DiskLocation) DeleteCollectionFromDiskLocation(collection string) (e er
|
||||
return
|
||||
}
|
||||
|
||||
func (l *DiskLocation) deleteVolumeById(vid needle.VolumeId, onlyEmpty bool) (found bool, e error) {
|
||||
func (l *DiskLocation) deleteVolumeById(vid needle.VolumeId, onlyEmpty bool, keepRemoteData bool) (found bool, e error) {
|
||||
v, ok := l.volumes[vid]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
e = v.Destroy(onlyEmpty)
|
||||
e = v.Destroy(onlyEmpty, keepRemoteData)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
@@ -359,7 +359,7 @@ func (l *DiskLocation) LoadVolume(diskId uint32, vid needle.VolumeId, needleMapK
|
||||
|
||||
var ErrVolumeNotFound = fmt.Errorf("volume not found")
|
||||
|
||||
func (l *DiskLocation) DeleteVolume(vid needle.VolumeId, onlyEmpty bool) error {
|
||||
func (l *DiskLocation) DeleteVolume(vid needle.VolumeId, onlyEmpty bool, keepRemoteData bool) error {
|
||||
l.volumesLock.Lock()
|
||||
defer l.volumesLock.Unlock()
|
||||
|
||||
@@ -367,7 +367,7 @@ func (l *DiskLocation) DeleteVolume(vid needle.VolumeId, onlyEmpty bool) error {
|
||||
if !ok {
|
||||
return ErrVolumeNotFound
|
||||
}
|
||||
_, err := l.deleteVolumeById(vid, onlyEmpty)
|
||||
_, err := l.deleteVolumeById(vid, onlyEmpty, keepRemoteData)
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -100,7 +99,7 @@ func RebuildEcFiles(baseFileName string, additionalDirs ...string) ([]uint32, er
|
||||
// RebuildEcFilesWithContext rebuilds missing EC files using the provided context.
|
||||
// additionalDirs are extra directories to search for existing shard files.
|
||||
func RebuildEcFilesWithContext(baseFileName string, ctx *ECContext, additionalDirs ...string) ([]uint32, error) {
|
||||
return generateMissingEcFiles(baseFileName, 256*1024, ErasureCodingLargeBlockSize, ErasureCodingSmallBlockSize, ctx, additionalDirs)
|
||||
return generateMissingEcFiles(baseFileName, ctx, additionalDirs)
|
||||
}
|
||||
|
||||
func ToExt(ecIndex int) string {
|
||||
@@ -128,44 +127,64 @@ func generateEcFiles(baseFileName string, bufferSize int, largeBlockSize int64,
|
||||
}
|
||||
|
||||
// findShardFile looks for a shard file at baseFileName+ext, then in additionalDirs.
|
||||
func findShardFile(baseFileName string, ext string, additionalDirs []string) string {
|
||||
primary := baseFileName + ext
|
||||
if util.FileExists(primary) {
|
||||
return primary
|
||||
}
|
||||
// Returns the first non-empty shard file path found. Any 0-byte residue files
|
||||
// (typically left behind by a previously aborted rebuild) are returned in ghosts
|
||||
// so the caller can remove them — otherwise they shadow real shards on the next
|
||||
// rebuild attempt and the volume gets silently mounted with empty stripes.
|
||||
func findShardFile(baseFileName string, ext string, additionalDirs []string) (shardPath string, shardSize int64, ghosts []string) {
|
||||
candidates := make([]string, 0, 1+len(additionalDirs))
|
||||
candidates = append(candidates, baseFileName+ext)
|
||||
baseName := filepath.Base(baseFileName)
|
||||
for _, dir := range additionalDirs {
|
||||
candidate := filepath.Join(dir, baseName+ext)
|
||||
if util.FileExists(candidate) {
|
||||
return candidate
|
||||
candidates = append(candidates, filepath.Join(dir, baseName+ext))
|
||||
}
|
||||
for _, c := range candidates {
|
||||
fi, statErr := os.Stat(c)
|
||||
if statErr != nil {
|
||||
continue
|
||||
}
|
||||
if fi.Size() == 0 {
|
||||
ghosts = append(ghosts, c)
|
||||
continue
|
||||
}
|
||||
if shardPath == "" {
|
||||
shardPath = c
|
||||
shardSize = fi.Size()
|
||||
}
|
||||
}
|
||||
return ""
|
||||
return
|
||||
}
|
||||
|
||||
func generateMissingEcFiles(baseFileName string, bufferSize int, largeBlockSize int64, smallBlockSize int64, ctx *ECContext, additionalDirs []string) (generatedShardIds []uint32, err error) {
|
||||
func generateMissingEcFiles(baseFileName string, ctx *ECContext, additionalDirs []string) (generatedShardIds []uint32, err error) {
|
||||
|
||||
// Pass 1: discover which shards exist and which are missing,
|
||||
// opening input files but NOT creating output files yet.
|
||||
shardHasData := make([]bool, ctx.Total())
|
||||
shardPaths := make([]string, ctx.Total()) // non-empty for present shards
|
||||
inputFiles := make([]*os.File, ctx.Total())
|
||||
var ghostPaths []string
|
||||
expectedShardSize := int64(-1)
|
||||
presentCount := 0
|
||||
for shardId := 0; shardId < ctx.Total(); shardId++ {
|
||||
ext := ctx.ToExt(shardId)
|
||||
shardPath := findShardFile(baseFileName, ext, additionalDirs)
|
||||
if shardPath != "" {
|
||||
shardHasData[shardId] = true
|
||||
shardPaths[shardId] = shardPath
|
||||
inputFiles[shardId], err = os.OpenFile(shardPath, os.O_RDONLY, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer inputFiles[shardId].Close()
|
||||
presentCount++
|
||||
} else {
|
||||
shardPath, shardSize, ghosts := findShardFile(baseFileName, ext, additionalDirs)
|
||||
ghostPaths = append(ghostPaths, ghosts...)
|
||||
if shardPath == "" {
|
||||
generatedShardIds = append(generatedShardIds, uint32(shardId))
|
||||
continue
|
||||
}
|
||||
if expectedShardSize < 0 {
|
||||
expectedShardSize = shardSize
|
||||
} else if shardSize != expectedShardSize {
|
||||
return nil, fmt.Errorf("ec shard size mismatch: %s is %d bytes, expected %d (refusing to rebuild from inconsistent shards)",
|
||||
shardPath, shardSize, expectedShardSize)
|
||||
}
|
||||
shardHasData[shardId] = true
|
||||
inputFiles[shardId], err = os.OpenFile(shardPath, os.O_RDONLY, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer inputFiles[shardId].Close()
|
||||
presentCount++
|
||||
}
|
||||
|
||||
// Pre-check: bail out before creating any output files.
|
||||
@@ -174,8 +193,8 @@ func generateMissingEcFiles(baseFileName string, bufferSize int, largeBlockSize
|
||||
baseFileName, presentCount, ctx.DataShards, generatedShardIds)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("rebuilding %s: %d shards present, %d missing %v, config %s",
|
||||
baseFileName, presentCount, len(generatedShardIds), generatedShardIds, ctx.String())
|
||||
glog.V(0).Infof("rebuilding %s: %d shards present (size %d), %d missing %v, %d ghost residue %v, config %s",
|
||||
baseFileName, presentCount, expectedShardSize, len(generatedShardIds), generatedShardIds, len(ghostPaths), ghostPaths, ctx.String())
|
||||
|
||||
// Pass 2: create output files for missing shards now that we know
|
||||
// reconstruction is possible.
|
||||
@@ -192,10 +211,32 @@ func generateMissingEcFiles(baseFileName string, bufferSize int, largeBlockSize
|
||||
defer outputFiles[shardId].Close()
|
||||
}
|
||||
|
||||
err = rebuildEcFiles(shardHasData, inputFiles, outputFiles, ctx)
|
||||
err = rebuildEcFiles(shardHasData, inputFiles, outputFiles, ctx, expectedShardSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("rebuildEcFiles: %w", err)
|
||||
}
|
||||
|
||||
// Reconstruction succeeded — remove any 0-byte residue from prior aborted
|
||||
// rebuilds so they don't shadow real shards on the next pass and don't get
|
||||
// mounted as empty stripes. Skip residue paths that the output-file step
|
||||
// has already overwritten with real data, since those entries in
|
||||
// ghostPaths refer to the just-rebuilt shard's location.
|
||||
freshOutputs := make(map[string]struct{}, len(outputFiles))
|
||||
for _, f := range outputFiles {
|
||||
if f != nil {
|
||||
freshOutputs[filepath.Clean(f.Name())] = struct{}{}
|
||||
}
|
||||
}
|
||||
for _, ghost := range ghostPaths {
|
||||
if _, overwritten := freshOutputs[filepath.Clean(ghost)]; overwritten {
|
||||
continue
|
||||
}
|
||||
if removeErr := os.Remove(ghost); removeErr != nil && !os.IsNotExist(removeErr) {
|
||||
glog.Warningf("failed to remove 0-byte ec shard residue %s: %v", ghost, removeErr)
|
||||
} else {
|
||||
glog.V(0).Infof("removed 0-byte ec shard residue %s", ghost)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -320,39 +361,42 @@ func encodeDatFile(remainingSize int64, baseFileName string, bufferSize int, lar
|
||||
return nil
|
||||
}
|
||||
|
||||
func rebuildEcFiles(shardHasData []bool, inputFiles []*os.File, outputFiles []*os.File, ctx *ECContext) error {
|
||||
func rebuildEcFiles(shardHasData []bool, inputFiles []*os.File, outputFiles []*os.File, ctx *ECContext, expectedShardSize int64) error {
|
||||
|
||||
enc, err := ctx.CreateEncoder()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create encoder: %w", err)
|
||||
}
|
||||
|
||||
// Pre-allocate buffers for every shard, including the missing ones we
|
||||
// need to reconstruct. reedsolomon.Reconstruct reuses cap when len==0
|
||||
// (cap(shard) >= shardSize → shard[0:shardSize]), so handing it a 0-len
|
||||
// slice with the right cap avoids a fresh allocation per chunk.
|
||||
buffers := make([][]byte, ctx.Total())
|
||||
for i := range buffers {
|
||||
if shardHasData[i] {
|
||||
buffers[i] = make([]byte, ErasureCodingSmallBlockSize)
|
||||
}
|
||||
buffers[i] = make([]byte, ErasureCodingSmallBlockSize)
|
||||
}
|
||||
|
||||
var startOffset int64
|
||||
var inputBufferDataSize int
|
||||
for {
|
||||
for startOffset := int64(0); startOffset < expectedShardSize; {
|
||||
chunkSize := int64(ErasureCodingSmallBlockSize)
|
||||
if remaining := expectedShardSize - startOffset; remaining < chunkSize {
|
||||
chunkSize = remaining
|
||||
}
|
||||
|
||||
// read the input data from files
|
||||
for i := 0; i < ctx.Total(); i++ {
|
||||
if shardHasData[i] {
|
||||
n, _ := inputFiles[i].ReadAt(buffers[i], startOffset)
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
if inputBufferDataSize == 0 {
|
||||
inputBufferDataSize = n
|
||||
}
|
||||
if inputBufferDataSize != n {
|
||||
return fmt.Errorf("ec shard size expected %d actual %d", inputBufferDataSize, n)
|
||||
buf := buffers[i][:chunkSize]
|
||||
n, readErr := inputFiles[i].ReadAt(buf, startOffset)
|
||||
if int64(n) != chunkSize {
|
||||
return fmt.Errorf("short read on shard %s at offset %d: got %d, want %d (err=%v)",
|
||||
inputFiles[i].Name(), startOffset, n, chunkSize, readErr)
|
||||
}
|
||||
buffers[i] = buf
|
||||
} else {
|
||||
buffers[i] = nil
|
||||
// 0-len, full-cap: signals "missing" while letting Reconstruct
|
||||
// reslice into our existing storage.
|
||||
buffers[i] = buffers[i][:0]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -365,15 +409,16 @@ func rebuildEcFiles(shardHasData []bool, inputFiles []*os.File, outputFiles []*o
|
||||
// write the data to output files
|
||||
for i := 0; i < ctx.Total(); i++ {
|
||||
if !shardHasData[i] {
|
||||
n, _ := outputFiles[i].WriteAt(buffers[i][:inputBufferDataSize], startOffset)
|
||||
if inputBufferDataSize != n {
|
||||
return fmt.Errorf("fail to write to %s", outputFiles[i].Name())
|
||||
n, writeErr := outputFiles[i].WriteAt(buffers[i][:chunkSize], startOffset)
|
||||
if int64(n) != chunkSize {
|
||||
return fmt.Errorf("short write to %s at offset %d: got %d, want %d (err=%v)",
|
||||
outputFiles[i].Name(), startOffset, n, chunkSize, writeErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
startOffset += int64(inputBufferDataSize)
|
||||
startOffset += chunkSize
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func readNeedleMap(baseFileName string) (*needle_map.MemDb, error) {
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
|
||||
)
|
||||
|
||||
// TestRebuildEcFiles_BasicTwoMissing covers the simple repair path: 12 of 14
|
||||
// shards present, 2 truly missing — must rebuild both and produce shards
|
||||
// identical to the originals.
|
||||
func TestRebuildEcFiles_BasicTwoMissing(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
base := filepath.Join(dir, "_109")
|
||||
originalShards := encodeFixture(t, base, 50*1024*1024)
|
||||
|
||||
// Drop shards 1 and 8.
|
||||
mustRemove(t, base+ToExt(1))
|
||||
mustRemove(t, base+ToExt(8))
|
||||
|
||||
rebuilt, err := RebuildEcFiles(base)
|
||||
if err != nil {
|
||||
t.Fatalf("RebuildEcFiles: %v", err)
|
||||
}
|
||||
sort.Slice(rebuilt, func(i, j int) bool { return rebuilt[i] < rebuilt[j] })
|
||||
if want := []uint32{1, 8}; !equalUint32(rebuilt, want) {
|
||||
t.Fatalf("rebuilt = %v, want %v", rebuilt, want)
|
||||
}
|
||||
|
||||
for _, idx := range []int{1, 8} {
|
||||
got := mustReadFile(t, base+ToExt(idx))
|
||||
if !bytes.Equal(got, originalShards[idx]) {
|
||||
t.Fatalf("shard %d content does not match the original encoding", idx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRebuildEcFiles_RejectsZeroByteResidue is the regression for issue #9340.
|
||||
//
|
||||
// When a previous ec.rebuild attempt aborts (e.g. crash, network error,
|
||||
// reedsolomon "too few shards" mid-rebuild), it leaves 0-byte placeholder
|
||||
// files for the shards it was about to write. On the next attempt, the old
|
||||
// findShardFile saw those 0-byte ghosts as "present", short-circuited the
|
||||
// reconstruction loop on the first n==0 read, and returned nil — making
|
||||
// ec.rebuild claim success while leaving the volume with empty shards.
|
||||
//
|
||||
// The fix: skip 0-byte files when scanning, treat the shards as still-missing,
|
||||
// and remove the residue after a successful rebuild so they don't shadow real
|
||||
// shards on the next pass.
|
||||
func TestRebuildEcFiles_RejectsZeroByteResidue(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
base := filepath.Join(dir, "_109")
|
||||
originalShards := encodeFixture(t, base, 50*1024*1024)
|
||||
|
||||
// Simulate the residue from a prior aborted rebuild: shard files for the
|
||||
// truly-missing shards exist on disk but are 0 bytes.
|
||||
for _, idx := range []int{1, 8} {
|
||||
mustRemove(t, base+ToExt(idx))
|
||||
mustWriteFile(t, base+ToExt(idx), nil)
|
||||
}
|
||||
|
||||
rebuilt, err := RebuildEcFiles(base)
|
||||
if err != nil {
|
||||
t.Fatalf("RebuildEcFiles: %v", err)
|
||||
}
|
||||
sort.Slice(rebuilt, func(i, j int) bool { return rebuilt[i] < rebuilt[j] })
|
||||
if want := []uint32{1, 8}; !equalUint32(rebuilt, want) {
|
||||
t.Fatalf("rebuilt = %v, want %v (the old code reported [] and silently left 0-byte residue)", rebuilt, want)
|
||||
}
|
||||
|
||||
for _, idx := range []int{1, 8} {
|
||||
fi, err := os.Stat(base + ToExt(idx))
|
||||
if err != nil {
|
||||
t.Fatalf("stat shard %d: %v", idx, err)
|
||||
}
|
||||
if fi.Size() == 0 {
|
||||
t.Fatalf("shard %d still 0 bytes after rebuild — residue was not cleared", idx)
|
||||
}
|
||||
got := mustReadFile(t, base+ToExt(idx))
|
||||
if !bytes.Equal(got, originalShards[idx]) {
|
||||
t.Fatalf("rebuilt shard %d does not match the original encoding", idx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRebuildEcFiles_ResidueOnAdditionalDisk reproduces the multi-disk variant
|
||||
// of the residue bug. The .ecx and the real shards live on the rebuild disk;
|
||||
// a sibling disk holds 0-byte placeholders for the shards that need to be
|
||||
// regenerated (e.g. an earlier rebuild crashed while writing them there). The
|
||||
// pre-fix findShardFile preferred the first existing path it saw — including
|
||||
// the 0-byte one — so the rebuild silently succeeded with empty stripes.
|
||||
func TestRebuildEcFiles_ResidueOnAdditionalDisk(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
disk1 := filepath.Join(root, "d1")
|
||||
disk2 := filepath.Join(root, "d2")
|
||||
mustMkdir(t, disk1)
|
||||
mustMkdir(t, disk2)
|
||||
|
||||
stagingBase := filepath.Join(root, "_109")
|
||||
originalShards := encodeFixture(t, stagingBase, 50*1024*1024)
|
||||
|
||||
// Real shards (except 1 and 8) and .vif live on disk1.
|
||||
disk1Base := filepath.Join(disk1, "_109")
|
||||
for i := 0; i < TotalShardsCount; i++ {
|
||||
if i == 1 || i == 8 {
|
||||
continue
|
||||
}
|
||||
mustRename(t, stagingBase+ToExt(i), disk1Base+ToExt(i))
|
||||
}
|
||||
mustRename(t, stagingBase+".vif", disk1Base+".vif")
|
||||
|
||||
// disk2 carries 0-byte residue for the missing shards.
|
||||
disk2Base := filepath.Join(disk2, "_109")
|
||||
for _, idx := range []int{1, 8} {
|
||||
mustWriteFile(t, disk2Base+ToExt(idx), nil)
|
||||
}
|
||||
|
||||
rebuilt, err := RebuildEcFiles(disk1Base, disk2)
|
||||
if err != nil {
|
||||
t.Fatalf("RebuildEcFiles: %v", err)
|
||||
}
|
||||
sort.Slice(rebuilt, func(i, j int) bool { return rebuilt[i] < rebuilt[j] })
|
||||
if want := []uint32{1, 8}; !equalUint32(rebuilt, want) {
|
||||
t.Fatalf("rebuilt = %v, want %v", rebuilt, want)
|
||||
}
|
||||
|
||||
for _, idx := range []int{1, 8} {
|
||||
got := mustReadFile(t, disk1Base+ToExt(idx))
|
||||
if !bytes.Equal(got, originalShards[idx]) {
|
||||
t.Fatalf("rebuilt shard %d on disk1 does not match the original", idx)
|
||||
}
|
||||
// Residue on the sibling disk must be cleaned up so it can't shadow
|
||||
// the real shard on a future scan.
|
||||
if _, err := os.Stat(disk2Base + ToExt(idx)); !os.IsNotExist(err) {
|
||||
t.Fatalf("shard %d residue on disk2 was not removed (err=%v)", idx, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRebuildEcFiles_RejectsMismatchedShardSizes ensures we surface a clear
|
||||
// error when surviving shards disagree on size, instead of feeding inconsistent
|
||||
// data into reedsolomon and producing corrupted output.
|
||||
func TestRebuildEcFiles_RejectsMismatchedShardSizes(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
base := filepath.Join(dir, "_109")
|
||||
encodeFixture(t, base, 50*1024*1024)
|
||||
|
||||
mustRemove(t, base+ToExt(1))
|
||||
// Truncate one surviving shard so its size disagrees with the others.
|
||||
if err := os.Truncate(base+ToExt(2), 1024); err != nil {
|
||||
t.Fatalf("truncate: %v", err)
|
||||
}
|
||||
|
||||
if _, err := RebuildEcFiles(base); err == nil {
|
||||
t.Fatalf("expected size-mismatch error, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
// encodeFixture writes a .dat file of the requested size, EC-encodes it, saves
|
||||
// a matching .vif, and returns a snapshot of every original shard's bytes.
|
||||
func encodeFixture(t *testing.T, baseFileName string, datSize int64) [TotalShardsCount][]byte {
|
||||
t.Helper()
|
||||
|
||||
data := make([]byte, datSize)
|
||||
if _, err := rand.Read(data); err != nil {
|
||||
t.Fatalf("rand: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(baseFileName+".dat", data, 0644); err != nil {
|
||||
t.Fatalf("write dat: %v", err)
|
||||
}
|
||||
if err := WriteEcFiles(baseFileName); err != nil {
|
||||
t.Fatalf("WriteEcFiles: %v", err)
|
||||
}
|
||||
|
||||
// A minimal .vif so RebuildEcFiles picks up the right ec config rather
|
||||
// than warning and falling back to defaults.
|
||||
vif := &volume_server_pb.VolumeInfo{
|
||||
Version: 3,
|
||||
DatFileSize: datSize,
|
||||
EcShardConfig: &volume_server_pb.EcShardConfig{
|
||||
DataShards: DataShardsCount,
|
||||
ParityShards: ParityShardsCount,
|
||||
},
|
||||
}
|
||||
if err := volume_info.SaveVolumeInfo(baseFileName+".vif", vif); err != nil {
|
||||
t.Fatalf("save vif: %v", err)
|
||||
}
|
||||
|
||||
var shards [TotalShardsCount][]byte
|
||||
for i := 0; i < TotalShardsCount; i++ {
|
||||
shards[i] = mustReadFile(t, baseFileName+ToExt(i))
|
||||
}
|
||||
return shards
|
||||
}
|
||||
|
||||
func mustRemove(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatalf("remove %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustWriteFile(t *testing.T, path string, data []byte) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, data, 0644); err != nil {
|
||||
t.Fatalf("write %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustReadFile(t *testing.T, path string) []byte {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", path, err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func mustRename(t *testing.T, from, to string) {
|
||||
t.Helper()
|
||||
if err := os.Rename(from, to); err != nil {
|
||||
t.Fatalf("rename %s -> %s: %v", from, to, err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustMkdir(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
t.Fatalf("mkdir %s: %v", dir, err)
|
||||
}
|
||||
}
|
||||
|
||||
func equalUint32(a, b []uint32) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// TestRebuildEcFiles_EightDiskTopology reproduces the user's reported topology
|
||||
// from #9340: a single volume server with 8 hdd locations
|
||||
// (/mnt/d{1..8}/weed), .ecx on one disk, the surviving local shard on another,
|
||||
// freshly-copied shards on a third, shards 1 and 8 truly missing. The volume
|
||||
// server's VolumeEcShardsRebuild picks the .ecx-owning disk as rebuildLocation
|
||||
// and passes every other disk as additionalDirs; we mirror that contract here.
|
||||
//
|
||||
// The test exercises:
|
||||
//
|
||||
// 1. Clean state — must rebuild shards 1 and 8 byte-identical to the
|
||||
// pre-removal originals.
|
||||
// 2. End-to-end decode — concatenating the data shards back through
|
||||
// WriteDatFile reproduces the original .dat byte-for-byte, proving the
|
||||
// rebuild is semantically correct (not just non-zero).
|
||||
// 3. Residue scenario — a previously aborted rebuild left 0-byte placeholders
|
||||
// for shards 1 and 8 on the rebuildLocation. Pre-fix this caused
|
||||
// findShardFile to return the ghost, the read loop to short-circuit on
|
||||
// n==0, and the rebuild to silently no-op. Post-fix the ghosts are
|
||||
// skipped, the rebuild succeeds, and the residue is removed.
|
||||
func TestRebuildEcFiles_EightDiskTopology(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
residueOn func(disks []string) [][2]string // (disk, ext) pairs to seed as 0-byte ghosts
|
||||
}{
|
||||
{name: "clean", residueOn: nil},
|
||||
{
|
||||
name: "residue_on_rebuild_disk",
|
||||
residueOn: func(disks []string) [][2]string {
|
||||
return [][2]string{
|
||||
{disks[1], ToExt(1)}, // d2 == rebuildLocation in this fixture
|
||||
{disks[1], ToExt(8)},
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "residue_on_sibling_disk",
|
||||
residueOn: func(disks []string) [][2]string {
|
||||
return [][2]string{
|
||||
{disks[3], ToExt(1)}, // a totally unrelated sibling disk
|
||||
{disks[6], ToExt(8)},
|
||||
}
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
runEightDiskRebuild(t, tc.residueOn)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func runEightDiskRebuild(t *testing.T, residueOn func(disks []string) [][2]string) {
|
||||
t.Helper()
|
||||
|
||||
root := t.TempDir()
|
||||
disks := make([]string, 8)
|
||||
for i := range disks {
|
||||
disks[i] = filepath.Join(root, "d"+string(rune('1'+i)), "weed")
|
||||
mustMkdir(t, disks[i])
|
||||
}
|
||||
|
||||
// Encode in a staging dir, then distribute shards across the 8 disks the
|
||||
// way the volume server would after a couple of rebuild rounds:
|
||||
// .ecx + .vif + a few shards on d2 (this is rebuildLocation), the
|
||||
// existing shard 2 on d1, copied shards spread across d3..d8.
|
||||
stagingBase := filepath.Join(root, "staging", "_109")
|
||||
mustMkdir(t, filepath.Dir(stagingBase))
|
||||
const datSize = int64(50 * 1024 * 1024)
|
||||
originalShards, originalDat := encodeFixtureWithDat(t, stagingBase, datSize)
|
||||
|
||||
rebuildLocation := disks[1] // d2 — owns .ecx
|
||||
homeDisk := []int{0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} // d1 holds shard 2 + most copied shards
|
||||
homeDisk[3], homeDisk[4], homeDisk[5], homeDisk[6], homeDisk[7] = 2, 3, 4, 5, 6 // spread a few copied shards to d3..d7
|
||||
homeDisk[10], homeDisk[11], homeDisk[12], homeDisk[13] = 7, 0, 1, 2 // and the rest across d8/d1/d2/d3
|
||||
missing := map[int]struct{}{1: {}, 8: {}}
|
||||
|
||||
rebuildBase := filepath.Join(rebuildLocation, "collect_109")
|
||||
mustRename(t, stagingBase+".vif", rebuildBase+".vif")
|
||||
if _, err := os.Stat(stagingBase + ".ecx"); err == nil {
|
||||
mustRename(t, stagingBase+".ecx", rebuildBase+".ecx")
|
||||
}
|
||||
for i := 0; i < TotalShardsCount; i++ {
|
||||
if _, gone := missing[i]; gone {
|
||||
mustRemove(t, stagingBase+ToExt(i))
|
||||
continue
|
||||
}
|
||||
dst := filepath.Join(disks[homeDisk[i]], "collect_109"+ToExt(i))
|
||||
mustRename(t, stagingBase+ToExt(i), dst)
|
||||
}
|
||||
|
||||
if residueOn != nil {
|
||||
for _, ent := range residueOn(disks) {
|
||||
ghost := filepath.Join(ent[0], "collect_109"+ent[1])
|
||||
mustWriteFile(t, ghost, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// Mirror VolumeEcShardsRebuild's contract: rebuildLocation is the disk
|
||||
// with .ecx; every other disk goes into additionalDirs.
|
||||
var additionalDirs []string
|
||||
for i, d := range disks {
|
||||
if i == 1 {
|
||||
continue
|
||||
}
|
||||
additionalDirs = append(additionalDirs, d)
|
||||
}
|
||||
|
||||
rebuilt, err := RebuildEcFiles(rebuildBase, additionalDirs...)
|
||||
if err != nil {
|
||||
t.Fatalf("RebuildEcFiles: %v", err)
|
||||
}
|
||||
sort.Slice(rebuilt, func(i, j int) bool { return rebuilt[i] < rebuilt[j] })
|
||||
if want := []uint32{1, 8}; !equalUint32(rebuilt, want) {
|
||||
t.Fatalf("rebuilt = %v, want %v", rebuilt, want)
|
||||
}
|
||||
|
||||
// Each rebuilt shard must match the original encoding bit-for-bit.
|
||||
for idx := range missing {
|
||||
got := mustReadFile(t, rebuildBase+ToExt(idx))
|
||||
if !bytes.Equal(got, originalShards[idx]) {
|
||||
t.Fatalf("rebuilt shard %d does not match the original encoding", idx)
|
||||
}
|
||||
}
|
||||
|
||||
// Any 0-byte residue we seeded on a sibling disk must be removed; residue
|
||||
// at the rebuild location's output path is fine — it gets overwritten.
|
||||
if residueOn != nil {
|
||||
for _, ent := range residueOn(disks) {
|
||||
ghost := filepath.Join(ent[0], "collect_109"+ent[1])
|
||||
if ent[0] == rebuildLocation {
|
||||
continue // overwritten by the output file
|
||||
}
|
||||
if _, statErr := os.Stat(ghost); !os.IsNotExist(statErr) {
|
||||
t.Fatalf("residue %s was not removed (statErr=%v)", ghost, statErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Decode all 10 data shards back through WriteDatFile and verify the
|
||||
// reconstructed .dat matches the original byte-for-byte. This is the real
|
||||
// safety check — non-zero rebuilt files aren't enough; they must contain
|
||||
// the right data.
|
||||
dataShardPaths := make([]string, DataShardsCount)
|
||||
for i := 0; i < DataShardsCount; i++ {
|
||||
if _, gone := missing[i]; gone {
|
||||
dataShardPaths[i] = rebuildBase + ToExt(i)
|
||||
continue
|
||||
}
|
||||
dataShardPaths[i] = filepath.Join(disks[homeDisk[i]], "collect_109"+ToExt(i))
|
||||
}
|
||||
decodedBase := filepath.Join(root, "decoded", "out")
|
||||
mustMkdir(t, filepath.Dir(decodedBase))
|
||||
if err := WriteDatFile(decodedBase, datSize, dataShardPaths); err != nil {
|
||||
t.Fatalf("WriteDatFile: %v", err)
|
||||
}
|
||||
decoded := mustReadFile(t, decodedBase+".dat")
|
||||
if !bytes.Equal(decoded, originalDat) {
|
||||
t.Fatalf("decoded .dat does not match original (len got=%d want=%d)", len(decoded), len(originalDat))
|
||||
}
|
||||
}
|
||||
|
||||
// encodeFixtureWithDat is encodeFixture but also returns the original .dat
|
||||
// bytes so the caller can verify a full encode→rebuild→decode round trip.
|
||||
func encodeFixtureWithDat(t *testing.T, baseFileName string, datSize int64) (shards [TotalShardsCount][]byte, dat []byte) {
|
||||
t.Helper()
|
||||
|
||||
dat = make([]byte, datSize)
|
||||
if _, err := rand.Read(dat); err != nil {
|
||||
t.Fatalf("rand: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(baseFileName+".dat", dat, 0644); err != nil {
|
||||
t.Fatalf("write dat: %v", err)
|
||||
}
|
||||
if err := WriteEcFiles(baseFileName); err != nil {
|
||||
t.Fatalf("WriteEcFiles: %v", err)
|
||||
}
|
||||
if err := WriteSortedFileFromIdx(baseFileName, ".ecx"); err != nil {
|
||||
// No .idx in this fixture (we don't run any reads), so this is best-effort.
|
||||
t.Logf("WriteSortedFileFromIdx (best-effort): %v", err)
|
||||
}
|
||||
vif := &volume_server_pb.VolumeInfo{
|
||||
Version: 3,
|
||||
DatFileSize: datSize,
|
||||
EcShardConfig: &volume_server_pb.EcShardConfig{
|
||||
DataShards: DataShardsCount,
|
||||
ParityShards: ParityShardsCount,
|
||||
},
|
||||
}
|
||||
if err := volume_info.SaveVolumeInfo(baseFileName+".vif", vif); err != nil {
|
||||
t.Fatalf("save vif: %v", err)
|
||||
}
|
||||
for i := 0; i < TotalShardsCount; i++ {
|
||||
shards[i] = mustReadFile(t, baseFileName+ToExt(i))
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
)
|
||||
|
||||
// In-process integration tests for cloud-tiered ("remote") volumes.
|
||||
//
|
||||
// Cover the operations the user is likely to schedule against a tiered
|
||||
// volume — balance/move, vacuum, EC encode, EC decode — exercising the real
|
||||
// Volume / DiskLocation / Store code paths against a fake BackendStorage that
|
||||
// stores objects in a temp dir. The fake stands in for S3/rclone/etc. so the
|
||||
// tests stay hermetic and fast.
|
||||
|
||||
// localDirBackend is a BackendStorage that stores objects as files in a
|
||||
// temp directory. It deletes from / writes to the dir under a mutex so the
|
||||
// tests can observe ordering (e.g. that a remote object survives a move).
|
||||
type localDirBackend struct {
|
||||
root string
|
||||
|
||||
mu sync.Mutex
|
||||
deletes []string // history of DeleteFile keys, for assertions
|
||||
}
|
||||
|
||||
func newLocalDirBackend(t *testing.T) *localDirBackend {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
return &localDirBackend{root: root}
|
||||
}
|
||||
|
||||
func (b *localDirBackend) ToProperties() map[string]string {
|
||||
return map[string]string{"root": b.root}
|
||||
}
|
||||
|
||||
func (b *localDirBackend) NewStorageFile(key string, tierInfo *volume_server_pb.VolumeInfo) backend.BackendStorageFile {
|
||||
return &localDirBackendFile{backend: b, key: key, tierInfo: tierInfo}
|
||||
}
|
||||
|
||||
func (b *localDirBackend) CopyFile(f *os.File, fn func(progressed int64, percentage float32) error) (key string, size int64, err error) {
|
||||
key = fmt.Sprintf("obj-%d-%d", time.Now().UnixNano(), os.Getpid())
|
||||
dst := filepath.Join(b.root, key)
|
||||
out, err := os.Create(dst)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
defer out.Close()
|
||||
if _, err = f.Seek(0, io.SeekStart); err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
written, err := io.Copy(out, f)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
if fn != nil {
|
||||
_ = fn(written, 100)
|
||||
}
|
||||
return key, written, nil
|
||||
}
|
||||
|
||||
func (b *localDirBackend) DownloadFile(fileName string, key string, fn func(progressed int64, percentage float32) error) (size int64, err error) {
|
||||
src := filepath.Join(b.root, key)
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer in.Close()
|
||||
out, err := os.Create(fileName)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer out.Close()
|
||||
written, err := io.Copy(out, in)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if fn != nil {
|
||||
_ = fn(written, 100)
|
||||
}
|
||||
return written, nil
|
||||
}
|
||||
|
||||
func (b *localDirBackend) DeleteFile(key string) error {
|
||||
b.mu.Lock()
|
||||
b.deletes = append(b.deletes, key)
|
||||
b.mu.Unlock()
|
||||
return os.Remove(filepath.Join(b.root, key))
|
||||
}
|
||||
|
||||
func (b *localDirBackend) deleteHistory() []string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
out := make([]string, len(b.deletes))
|
||||
copy(out, b.deletes)
|
||||
return out
|
||||
}
|
||||
|
||||
func (b *localDirBackend) objectExists(key string) bool {
|
||||
_, err := os.Stat(filepath.Join(b.root, key))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// localDirBackendFile satisfies BackendStorageFile by reading/writing through
|
||||
// the file in the temp dir keyed by the .vif's stored object key. Size and
|
||||
// modtime come from the cached tierInfo, mirroring the S3 backend's
|
||||
// behavior of returning .vif metadata from GetStat.
|
||||
type localDirBackendFile struct {
|
||||
backend *localDirBackend
|
||||
key string
|
||||
tierInfo *volume_server_pb.VolumeInfo
|
||||
}
|
||||
|
||||
func (f *localDirBackendFile) ReadAt(p []byte, off int64) (int, error) {
|
||||
in, err := os.Open(filepath.Join(f.backend.root, f.key))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer in.Close()
|
||||
return in.ReadAt(p, off)
|
||||
}
|
||||
|
||||
func (f *localDirBackendFile) WriteAt(p []byte, off int64) (int, error) {
|
||||
out, err := os.OpenFile(filepath.Join(f.backend.root, f.key), os.O_RDWR|os.O_CREATE, 0o644)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer out.Close()
|
||||
return out.WriteAt(p, off)
|
||||
}
|
||||
|
||||
func (f *localDirBackendFile) Truncate(off int64) error {
|
||||
return os.Truncate(filepath.Join(f.backend.root, f.key), off)
|
||||
}
|
||||
|
||||
func (f *localDirBackendFile) Close() error { return nil }
|
||||
func (f *localDirBackendFile) Name() string { return f.key }
|
||||
func (f *localDirBackendFile) Sync() error { return nil }
|
||||
func (f *localDirBackendFile) GetStat() (int64, time.Time, error) {
|
||||
files := f.tierInfo.GetFiles()
|
||||
if len(files) == 0 {
|
||||
return 0, time.Time{}, fmt.Errorf("remote file info not found")
|
||||
}
|
||||
return int64(files[0].FileSize), time.Unix(int64(files[0].ModifiedTime), 0), nil
|
||||
}
|
||||
|
||||
const (
|
||||
testBackendName = "test_local_dir.default"
|
||||
)
|
||||
|
||||
// registerTestBackend installs the fake backend in the global registry under
|
||||
// testBackendName for the duration of one test. Volume.Destroy and tier
|
||||
// upload look this map up by name, so the registration must outlive the
|
||||
// volume operations exercised below.
|
||||
func registerTestBackend(t *testing.T, b *localDirBackend) {
|
||||
t.Helper()
|
||||
backend.BackendStorages[testBackendName] = b
|
||||
t.Cleanup(func() {
|
||||
delete(backend.BackendStorages, testBackendName)
|
||||
})
|
||||
}
|
||||
|
||||
// tierUpVolume creates a real on-disk volume, writes a few needles, then
|
||||
// uploads the .dat to the fake backend and rewrites the volume in remote
|
||||
// mode (mirrors the production flow in volume_grpc_tier_upload.go but
|
||||
// in-process).
|
||||
func tierUpVolume(t *testing.T, dir string, vid needle.VolumeId, b *localDirBackend) (collection string, key string) {
|
||||
t.Helper()
|
||||
v, err := NewVolume(dir, dir, "", vid, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
|
||||
require.NoError(t, err)
|
||||
|
||||
for i := 1; i <= 5; i++ {
|
||||
_, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(i)), true, false)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
diskFile, ok := v.DataBackend.(*backend.DiskFile)
|
||||
require.True(t, ok, "expected on-disk backend before tier-up")
|
||||
|
||||
uploadKey, size, err := b.CopyFile(diskFile.File, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
bType, bId := backend.BackendNameToTypeId(testBackendName)
|
||||
v.GetVolumeInfo().Files = append(v.GetVolumeInfo().GetFiles(), &volume_server_pb.RemoteFile{
|
||||
BackendType: bType,
|
||||
BackendId: bId,
|
||||
Key: uploadKey,
|
||||
Offset: 0,
|
||||
FileSize: uint64(size),
|
||||
ModifiedTime: uint64(time.Now().Unix()),
|
||||
Extension: ".dat",
|
||||
})
|
||||
require.NoError(t, v.SaveVolumeInfo())
|
||||
require.NoError(t, v.LoadRemoteFile())
|
||||
require.NoError(t, os.Remove(v.FileName(".dat")))
|
||||
|
||||
// Close the volume cleanly. Tests below reload it from disk to mirror
|
||||
// what a volume server does on restart with a tiered volume.
|
||||
v.Close()
|
||||
|
||||
return v.Collection, uploadKey
|
||||
}
|
||||
|
||||
// reloadVolume loads an existing volume from disk, the way a volume server
|
||||
// does at startup. Returns the live volume with its async write worker
|
||||
// running, so Destroy's channel close is valid.
|
||||
func reloadVolume(t *testing.T, dir string, vid needle.VolumeId) *Volume {
|
||||
t.Helper()
|
||||
v, err := NewVolume(dir, dir, "", vid, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
|
||||
require.NoError(t, err)
|
||||
return v
|
||||
}
|
||||
|
||||
// TestRemoteTier_Move_KeepsRemoteObject simulates the move-on-source-after-copy
|
||||
// step of a balance: Destroy(onlyEmpty=false, keepRemoteData=true). The remote
|
||||
// object must survive — the destination's freshly-copied .vif points at it.
|
||||
func TestRemoteTier_Move_KeepsRemoteObject(t *testing.T) {
|
||||
b := newLocalDirBackend(t)
|
||||
registerTestBackend(t, b)
|
||||
|
||||
dir := t.TempDir()
|
||||
const vid = needle.VolumeId(31)
|
||||
_, key := tierUpVolume(t, dir, vid, b)
|
||||
require.True(t, b.objectExists(key), "remote object missing after tier-up")
|
||||
|
||||
v := reloadVolume(t, dir, vid)
|
||||
require.True(t, v.HasRemoteFile())
|
||||
|
||||
require.NoError(t, v.Destroy(false, true))
|
||||
|
||||
require.True(t, b.objectExists(key), "Destroy(keepRemoteData=true) must not delete remote object")
|
||||
require.Empty(t, b.deleteHistory(), "no DeleteFile call expected on a move-style destroy")
|
||||
}
|
||||
|
||||
// TestRemoteTier_RealDelete_RemovesRemoteObject is the inverse: a true delete
|
||||
// (keepRemoteData=false) must clean up the remote object. Locks in that we
|
||||
// did not accidentally turn the new flag into a global skip.
|
||||
func TestRemoteTier_RealDelete_RemovesRemoteObject(t *testing.T) {
|
||||
b := newLocalDirBackend(t)
|
||||
registerTestBackend(t, b)
|
||||
|
||||
dir := t.TempDir()
|
||||
const vid = needle.VolumeId(32)
|
||||
_, key := tierUpVolume(t, dir, vid, b)
|
||||
|
||||
v := reloadVolume(t, dir, vid)
|
||||
require.True(t, v.HasRemoteFile())
|
||||
|
||||
require.NoError(t, v.Destroy(false, false))
|
||||
|
||||
require.False(t, b.objectExists(key), "Destroy(keepRemoteData=false) must delete remote object")
|
||||
require.Equal(t, []string{key}, b.deleteHistory())
|
||||
}
|
||||
|
||||
// TestRemoteTier_Vacuum_DoesNotDeleteRemote runs the compact paths against a
|
||||
// remote-tier volume and asserts the safety property: regardless of whether
|
||||
// compact succeeds, errors, or no-ops, it must not delete the cloud object.
|
||||
func TestRemoteTier_Vacuum_DoesNotDeleteRemote(t *testing.T) {
|
||||
b := newLocalDirBackend(t)
|
||||
registerTestBackend(t, b)
|
||||
|
||||
dir := t.TempDir()
|
||||
const vid = needle.VolumeId(33)
|
||||
_, key := tierUpVolume(t, dir, vid, b)
|
||||
require.True(t, b.objectExists(key))
|
||||
|
||||
v := reloadVolume(t, dir, vid)
|
||||
defer v.Close()
|
||||
require.True(t, v.HasRemoteFile())
|
||||
|
||||
_ = v.CompactByVolumeData(nil)
|
||||
_ = v.CompactByIndex(nil)
|
||||
require.True(t, b.objectExists(key), "Compact must not delete remote object")
|
||||
require.Empty(t, b.deleteHistory())
|
||||
}
|
||||
|
||||
// TestRemoteTier_ECEncode_RequiresLocalDat confirms the EC encoder runs
|
||||
// against the local .dat path. For a remote-tier volume the .dat is gone,
|
||||
// so encoding is expected to fail with a missing-file error — locks in that
|
||||
// callers must download (tier_move_dat_from_remote) before encoding.
|
||||
func TestRemoteTier_ECEncode_RequiresLocalDat(t *testing.T) {
|
||||
b := newLocalDirBackend(t)
|
||||
registerTestBackend(t, b)
|
||||
|
||||
dir := t.TempDir()
|
||||
const vid = needle.VolumeId(34)
|
||||
tierUpVolume(t, dir, vid, b)
|
||||
|
||||
baseFileName := filepath.Join(dir, fmt.Sprintf("%d", uint32(vid)))
|
||||
err := erasure_coding.WriteEcFiles(baseFileName)
|
||||
require.Error(t, err, "EC encoder must not run with .dat missing — caller is expected to download first")
|
||||
require.Contains(t, err.Error(), ".dat")
|
||||
}
|
||||
|
||||
// TestRemoteTier_ECEncodeDecode_AfterDownload exercises the encode/decode
|
||||
// round-trip on a tiered volume after pulling the .dat back to local disk
|
||||
// (the production sequence used by `volume.tier.move -dest=local`).
|
||||
func TestRemoteTier_ECEncodeDecode_AfterDownload(t *testing.T) {
|
||||
b := newLocalDirBackend(t)
|
||||
registerTestBackend(t, b)
|
||||
|
||||
dir := t.TempDir()
|
||||
const vid = needle.VolumeId(35)
|
||||
_, key := tierUpVolume(t, dir, vid, b)
|
||||
|
||||
baseFileName := filepath.Join(dir, fmt.Sprintf("%d", uint32(vid)))
|
||||
datPath := baseFileName + ".dat"
|
||||
_, err := b.DownloadFile(datPath, key, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NoError(t, erasure_coding.WriteSortedFileFromIdx(baseFileName, ".ecx"))
|
||||
require.NoError(t, erasure_coding.WriteEcFiles(baseFileName))
|
||||
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
shardPath := fmt.Sprintf("%s.ec%02d", baseFileName, i)
|
||||
_, statErr := os.Stat(shardPath)
|
||||
require.NoError(t, statErr, "shard %d missing after encode", i)
|
||||
}
|
||||
|
||||
// Drop the parity-range shards (indices DataShardsCount..TotalShardsCount-1)
|
||||
// and rebuild — exercises the recover-from-missing-parity path.
|
||||
for i := erasure_coding.DataShardsCount; i < erasure_coding.TotalShardsCount; i++ {
|
||||
shardPath := fmt.Sprintf("%s.ec%02d", baseFileName, i)
|
||||
require.NoError(t, os.Remove(shardPath))
|
||||
}
|
||||
rebuilt, err := erasure_coding.RebuildEcFiles(baseFileName)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, rebuilt, "rebuild should report which parity shards were regenerated")
|
||||
for i := erasure_coding.DataShardsCount; i < erasure_coding.TotalShardsCount; i++ {
|
||||
shardPath := fmt.Sprintf("%s.ec%02d", baseFileName, i)
|
||||
_, statErr := os.Stat(shardPath)
|
||||
require.NoError(t, statErr, "parity shard %d missing after rebuild", i)
|
||||
}
|
||||
}
|
||||
+11
-4
@@ -394,7 +394,12 @@ func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
|
||||
collectionVolumeDeletedBytes := make(map[string]int64)
|
||||
collectionVolumeReadOnlyCount := make(map[string]map[string]uint8)
|
||||
for _, location := range s.Locations {
|
||||
// keepRemoteData is parallel to deleteVids: true entries preserve the
|
||||
// cloud-tier object on Volume.Destroy. IO-error deletions on a
|
||||
// remote-tiered volume must not nuke the remote object — the error
|
||||
// is local/transient and the cloud copy is the source of truth.
|
||||
var deleteVids []needle.VolumeId
|
||||
var keepRemoteData []bool
|
||||
effectiveMaxCount := location.MaxVolumeCount
|
||||
if location.isDiskSpaceLow {
|
||||
usedSlots := int32(location.LocalVolumesLen())
|
||||
@@ -419,6 +424,7 @@ func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
|
||||
|
||||
if v.lastIoError != nil {
|
||||
deleteVids = append(deleteVids, v.Id)
|
||||
keepRemoteData = append(keepRemoteData, v.HasRemoteFile())
|
||||
shouldDeleteVolume = true
|
||||
glog.Warningf("volume %d has IO error: %v", v.Id, v.lastIoError)
|
||||
} else {
|
||||
@@ -428,6 +434,7 @@ func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
|
||||
if v.expiredLongEnough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
|
||||
if !shouldDeleteVolume {
|
||||
deleteVids = append(deleteVids, v.Id)
|
||||
keepRemoteData = append(keepRemoteData, false)
|
||||
shouldDeleteVolume = true
|
||||
}
|
||||
} else {
|
||||
@@ -476,8 +483,8 @@ func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
|
||||
if len(deleteVids) > 0 {
|
||||
// delete expired volumes.
|
||||
location.volumesLock.Lock()
|
||||
for _, vid := range deleteVids {
|
||||
found, err := location.deleteVolumeById(vid, false)
|
||||
for i, vid := range deleteVids {
|
||||
found, err := location.deleteVolumeById(vid, false, keepRemoteData[i])
|
||||
if err == nil {
|
||||
if found {
|
||||
glog.V(0).Infof("volume %d is deleted", vid)
|
||||
@@ -725,7 +732,7 @@ func (s *Store) UnmountVolume(i needle.VolumeId) error {
|
||||
return fmt.Errorf("volume %d not found on disk", i)
|
||||
}
|
||||
|
||||
func (s *Store) DeleteVolume(i needle.VolumeId, onlyEmpty bool) error {
|
||||
func (s *Store) DeleteVolume(i needle.VolumeId, onlyEmpty bool, keepRemoteData bool) error {
|
||||
v := s.findVolume(i)
|
||||
if v == nil {
|
||||
return fmt.Errorf("delete volume %d not found on disk", i)
|
||||
@@ -740,7 +747,7 @@ func (s *Store) DeleteVolume(i needle.VolumeId, onlyEmpty bool) error {
|
||||
DiskId: v.diskId,
|
||||
}
|
||||
for _, location := range s.Locations {
|
||||
err := location.DeleteVolume(i, onlyEmpty)
|
||||
err := location.DeleteVolume(i, onlyEmpty, keepRemoteData)
|
||||
if err == nil {
|
||||
glog.V(0).Infof("DeleteVolume %d", i)
|
||||
s.DeletedVolumesChan <- message
|
||||
|
||||
@@ -2,6 +2,7 @@ package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -22,6 +23,12 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
// errShardNotLocal indicates that the requested EC shard is simply not
|
||||
// stored on this volume server. It is expected during normal reads when
|
||||
// shards are spread across multiple servers, so callers should not log
|
||||
// it as an error.
|
||||
var errShardNotLocal = errors.New("ec shard not on this server")
|
||||
|
||||
// FindEcShardTargetLocation returns the disk that should receive a new
|
||||
// shard / index file for (collection, vid). The selection order is:
|
||||
//
|
||||
@@ -317,7 +324,12 @@ func (s *Store) readOneEcShardInterval(needleId types.NeedleId, ecVolume *erasur
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
glog.V(0).Infof("read local ec shard %d.%d offset %d: %v", ecVolume.VolumeId, shardId, actualOffset, err)
|
||||
if errors.Is(err, errShardNotLocal) {
|
||||
// expected when shards are spread across servers; fall through to remote read
|
||||
glog.V(4).Infof("ec shard %d.%d not local, will try remote", ecVolume.VolumeId, shardId)
|
||||
} else {
|
||||
glog.V(0).Infof("read local ec shard %d.%d offset %d: %v", ecVolume.VolumeId, shardId, actualOffset, err)
|
||||
}
|
||||
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
sourceDataNodes, hasShardIdLocation := ecVolume.ShardLocations[shardId]
|
||||
@@ -395,7 +407,7 @@ func (s *Store) cachedLookupEcShardLocations(ecVolume *erasure_coding.EcVolume)
|
||||
func (s *Store) readLocalEcShardInterval(ecVolume *erasure_coding.EcVolume, shardId erasure_coding.ShardId, buf []byte, offset int64) error {
|
||||
shard, found := ecVolume.FindEcVolumeShard(shardId)
|
||||
if !found {
|
||||
return fmt.Errorf("shard %d not found for volume %d", shardId, ecVolume.VolumeId)
|
||||
return fmt.Errorf("shard %d for volume %d: %w", shardId, ecVolume.VolumeId, errShardNotLocal)
|
||||
}
|
||||
|
||||
readBytes, err := shard.ReadAt(buf, offset)
|
||||
|
||||
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user