mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-09-20 13:30:46 +02:00
* filer: stamp a log position on lookup and remote-cache responses Metadata events are logged after their store write and stamped with the filer clock. Reading that clock before serving an entry therefore gives a timestamp with a causal guarantee: every event at or below it is reflected in the returned entry. Clients caching filer state can use it as the entry's version to order the response against subscription events, including events committed before the call but delivered after it. * mount: version open file handles by filer log position A subscription event refreshing an open handle did a second lookup; a transient failure left the handle pinned to its old entry with no retry, since the subscription cursor had already advanced. The deeper problem is ordering: the handle is a cache written by three unordered channels — the async invalidation worker, local mutation acks, and open-time lookups — and overwriting cached state safely requires knowing which write is newer. The filer log timestamp is that order, and it now travels with every value instead of being derived out of band. Events carry it natively; lookup and remote-cache responses carry the log position stamped before the serving read; mutation acks carry it in their returned event; and the local store pairs each read with a version cursor advanced under the same lock as the store write. Each handle records the version its entry reflects, and one rule replaces the per-site reasoning: state at or below the handle's version is old news and must not be installed. The invalidation itself applies the event's own entry — no lookup, so no transient-failure window — except under a cached parent, where the store entry is the ordered merge of the event and anything applied since, and its version outranks the event's. An uncached parent receives no store writes, so a hit there would be a stale leftover masking the event. A vacated path (delete, rename away) keeps the last entry so unlinked-but-open reads still work. Directory builds version the completed directory at the listing snapshot and re-invalidate buffered events at that version, since their mid-build refresh ran against an incomplete store. The tests replay every race this replaces machinery for: rollback of a newer local flush (queued, cached, and read-through), stale leftovers under uncached parents, the build window including abort, handles opened after an event was queued, events landing mid-lookup, and undelivered events at remote-cache time across a filer failover. * filer: serialize the log position fence with mutations, stamp mutation acks The fence stamped before an unlocked entry read could precede state the read returned: a mutation writes storage first and assigns its event timestamp only at notify time, so a lookup racing that window handed the mount an entry newer than its fence, and the event's later delivery looked like fresh news — destroying dirty pages for a change the handle already had. The mutation handlers already hold an exclusive per-path lock across read, write, and notify; the lookup and remote-cache reads now take it shared around the stamp and the read, making the fence exact: everything at or below it is in the entry, nothing above it is. A no-change update returns success without an event, leaving the mount nothing to fence with even though the response confirms current state. Create and update acks now carry a log position stamped under the same lock, and the mount falls back to it whenever the ack has no event. Also regenerate the VT marshalers, which the earlier generation missed: without them a VT round-trip silently zeroed every log position. * java: sync filer.proto * mount: scope store versions to what they vouch for; atomic handle install The store's version cursor claimed too much. Advanced by local mutation acks and directory listing snapshots, it inflated the version of store reads for unrelated paths whose events the subscription still owed, and those events were then fenced out permanently. The cursor now tracks subscription progress only — events arrive in log order, so everything at or below it has been delivered for every path — and a completed listing records its snapshot as a per-directory floor instead of a global claim. Local acks never touch it: they version their own handle directly. Buffered build events advance the cursor at delivery, since their store write may never happen (abort) while their invalidation is already queued; their read-through directory pairs no store read with it, and rename fragments are applied first. Concurrent first opens raced: a slower opener's older lookup could overwrite the newer entry a faster opener had installed, while the monotonic version kept the newer timestamp — an old entry fenced at a new version, immune to every correcting event. Entry and version are now installed as one decision under the handle map lock, and an install that does not outrank the handle's version is dropped. The remote-cache commit also escaped the fence: it wrote storage and notified without the path lock, so a lookup's shared-locked fence and read could land between the two and hand out the cached state under-versioned. The commit now re-reads and writes under the exclusive path lock, and backs off entirely when the entry changed during the download — the concurrent writer supersedes the cached content. * mount: floors gate store applies; installs respect handle users; renames join the fence A directory floor certifies the listing state as of its snapshot, but a delayed event at or below the floor was still applied to the store — rolling the content back to pre-snapshot state while the floor kept claiming the snapshot version, so the correcting events were fenced out of every future read. Events are now gated against the affected directory's floor, each half of a rename independently. Fences are lower bounds: a listing or lookup can include a mutation whose event has not been delivered yet, and that event later passes every gate carrying state the handle already holds. Such a re-delivery now advances the version without destroying dirty pages or reinstalling the entry — invalidating local writes over a no-op was the real damage in every remaining under-fence window, including the unlocked listing snapshot, which no per-path lock can serialize. The concurrent-open install moved from the map lock to the handle lock every reader, writer, and invalidation synchronizes on, and rejects what cannot improve the handle: dirty state (local writes would be lost), unversioned lookup responses (they cannot outrank anything, and two zero-version opens must not overwrite each other), and anything not strictly newer. New handles are still fully initialized before the map exposes them. Renames committed metadata and emitted events with no path lock, so a lookup could read the renamed state under a fence preceding its events. Both rename handlers now hold the source and destination locks, ordered by path, across commit and notification; descendants of a renamed directory are not individually locked and rely on the no-op re-delivery handling above. * mount: per-entry store versions replace the cursor and directory floors The store's aggregate versions — a global subscription cursor and per-directory listing floors — were versions at coarser granularity than the values they described, and every over-claiming bug in this series traced to that gap: an aggregate vouching for state its source never saw. Each store entry now carries the filer log position of the write that produced it — the event that applied it, or the listing snapshot that inserted it, recorded in the store's key-value space under the same lock as the entry write. The store becomes what the handle already is: a last-writer-wins register with one rule, install only what outranks the current claim. The cursor, the floors, their advancement rules, the pairing ordering constraint, and the floor gating all collapse into that rule. Applies are gated per entry, each half of a rename independently; an unversioned local write clears the claim its content no longer proves; version records lingering after a bulk folder wipe cannot fence a recreate, since a claim only blocks while its entry exists. Listing inserts are stamped at build completion, before the buffered replay so newer replayed events override the stamp. Filer side, the fence dance every versioned read must perform is now a single choke point, fencedFindEntry, so a future read RPC gets the lock-serialized stamp by construction rather than by convention. * mount: judge no-op re-deliveries against an immutable base, not the live entry The equal-state skip compared the incoming event to the live handle entry, but local writes mutate the live entry — size, timestamps, chunks — so a delayed event re-delivering the base the handle was opened with no longer matched, and the installer destroyed the dirty pages and rolled the entry back over nothing new. The handle now keeps an immutable snapshot of the filer state it last installed or acknowledged, refreshed at every install and mutation ack (flush acks snapshot the request entry before the id mapping mutates it), and the no-op judgment runs against that base: an event carrying the base brings nothing, whatever the live entry has diverged to since. * mount: tombstones for versioned deletes, absence floors, copy enrollment Four gaps in the per-entry version protocol, all the same shape: a versioned fact with nothing carrying its version. A deletion is a fact about a path with no entry left to hold it — clearing the record let a delayed older event resurrect the deleted path, permanently, since the deletion's own redelivery is dedup-suppressed. Versioned deletes now leave a tombstone record that fences without an entry; renames tombstone their source the same way. Plain records still only block while their entry exists, so records lingering after a bulk folder wipe cannot fence a recreate. A completed listing proves absences as well as presences: a name it omitted was deleted as of the snapshot, and a delayed create below the snapshot re-creates it. The snapshot is kept per directory strictly as an absence fence, consulted only when a path has neither an entry nor a version record — present entries carry their own versions and never touch it, which is what separates this from the over-claiming floor it replaces. A rebuild against a pre-upgrade filer returns no snapshot; stamping now clears the children's records in that case, so a reinserted entry cannot reactivate the stale claim its previous incarnation left behind and reject valid events below it. Server-side copies installed the copied entry without enrolling in the base protocol, so the copy's own event differed from the stale pre-copy base and destroyed writes made to the destination after the copy. The install now refreshes the base and takes its version from the fenced readback. * mount: deletion facts outlive the cache's knowledge of the entry A versioned delete of a path the store held no entry for recorded nothing, so a delayed older event recreated the path — permanently, with the deletion's redelivery dedup-suppressed. The tombstone is now written whenever a versioned event vacates a path: the deletion is a fact about the path, not about what this cache happened to hold. For an absent entry, the listing's absence floor now speaks whatever older record remains: a tombstone at one position does not exhaust what is known about the path when a newer snapshot has confirmed the name still absent, and an event between the two was slipping past both. A committed copy whose readback failed installed a synthesized base with local timestamps; the copy's real event legitimately differs from it, and was read as foreign state — destroying writes made to the destination after the copy. The handle now marks that its own event is en route and adopts that event's state as the base without touching the live entry or the dirty pages; the adoption is one-shot, so a genuinely foreign event still invalidates. * mount: authoritative acks cancel pending event adoption; tombstones scoped and pruned The copy-event adoption flag could outlive its purpose: a flush after the failed readback installs a newer base and advances the version, the copy's own event is then version gated without consuming the flag, and the next genuinely foreign event was silently adopted — base advanced, live entry and dirty pages untouched — leaving the mount to later overwrite that remote change. Every local acknowledgment now installs its base through one helper that also cancels any pending adoption: the ack supersedes the mutation the adoption was waiting for. Tombstones were written for every versioned delete under the mount and survived directory eviction by design, growing LevelDB with historical deletions on delete-heavy mounts. They are now scoped to directories whose cached state the fence actually protects — an uncached parent never serves from the store nor applies the resurrecting insert — and a completed listing prunes the direct-child tombstones its absence floor supersedes, leaving only those above the snapshot. The store gains a key-prefix visitor for the sweep. * mount: acked saves install their value; trailer snapshots; direct-child prune range A version must never advance without its value. saveEntry stamped any open handle with the acknowledgment's version, but a handle opened while the save was in flight holds the pre-mutation entry — stamping it fenced out the events carrying the state it lacked, permanently, with the local apply performing no invalidation and the redelivery deduplicated. The acknowledged entry is now installed together with its version, through the same guarded install the racing-open path uses: under the handle lock, only when it outranks the handle, never over dirty local writes. Empty listings return no in-band snapshot — a snapshot-only response would be read as an entry by older consumers — so directories that end empty gained no absence floor and their tombstones were never pruned. The filer now sends the snapshot in the stream trailer, which older clients ignore, and the client reads it when no in-band snapshot arrived. Empty directories get real floors, their tombstones prune, and their buffered replays gain the snapshot filter instead of the replay-all fallback. Version records now encode the parent directory and name separated by a NUL, making a directory's direct children one contiguous key range: the tombstone prune scans exactly them under the cache lock, instead of walking every descendant record — the whole store, for root. * mount: fix dirty-page loss, uid/gid base, download race, copy adopt, leak; dedup Correctness fixes from the versioned-invalidation review: - A foreign delete/rename-away of a file held open with unflushed local writes destroyed the dirty pages unconditionally. A process may keep writing to an unlinked-but-open file and those writes were already acknowledged; preserve the pages when the handle is dirty. - downloadRemoteEntry stored the handle's base with filer-side uid/gid while every candidate it is later compared against is in local form, so under a non-identity UidGidMapper an unchanged re-delivery looked foreign and force-destroyed dirty pages. Map the base to local. - downloadRemoteEntry wrote the entry/base/version triple under only the handle's shared lock, so two concurrent reads of the same remote-only file could tear it. Serialize the install with a dedicated mutex (invalidation is already excluded by the exclusive handle lock). - A committed server-side copy whose readback failed adopted the FIRST event past the version gate as its base; a foreign write delivered first was silently swallowed. Adopt only an event whose content matches the synthesized base — the copy's own event — and install any other normally. - The deferred-create path relied on AcquireFileHandle installing the passed entry on a pre-existing handle, which the version rework dropped. Restore that install in the compat wrapper; the versioned open path keeps its gated install. Growth and hot-path cost: - Per-entry version records and tombstones leaked when a directory was evicted or read-through without a rebuild. An uncached directory gates its own inserts, so its records fence nothing; clear a directory's child version records when it is wiped for eviction. - FindEntry paid for the version KvGet on every lookup/getattr cache hit and threw it away. FindEntry now reads only the entry; the hot lookupEntry cache-hit path skips the version entirely. Cleanups: - Extract ackVersionTsNs over the shared response interface, replacing the metadata-event-else-log-ts snippet copy-pasted at four ack sites. - Extract acquireRenamePathLocks, replacing the verbatim sorted two-path lock fence in both rename handlers. * mount: no resurrection on foreign delete, version no-event acks, gate downloads, tighten copy adopt Follow-ups to the review patches: - Preserving dirty pages on a foreign delete let the next flush pass the isDeleted guard and CreateEntry, resurrecting the remotely-unlinked name. Mark the handle deleted in the vacate branch: the open fd can still read its buffered writes, but a flush no longer recreates the file. - A no-event acknowledgment (log fence only) synthesized a metadata event with TsNs 0, so the cache stored the entry unversioned and an older subscriber event rolled it back. Stamp the synthesized event with the ack's log position at all four ack sites. - downloadRemoteEntry serialized its install but did not check the version, so an older response arriving last overwrote the entry/base while the monotonic version kept the newer value, fencing corrections out. Install only when the response is at least as new as the handle. - sameEntryContent compared only size and chunks, so a foreign chmod with unchanged content was adopted as the copy's own event. Compare everything except server-assigned timestamps, so a metadata-only foreign change installs instead. * mount: trim comments to the non-obvious why The versioning work accumulated multi-line comment blocks restating what the code says. Keep the constraint a reader cannot derive — why a fence is exact, why a version must not advance without its value, why an uncached parent's records fence nothing — and drop the rest. * mount: distinguish rename from delete, tighten the download and adopt gates - A rename emits a nil old-path invalidation just like an unlink, so the vacate branch marked the handle deleted and later writes through the already-open descriptor were skipped instead of persisted. Carry the delete/rename distinction on the invalidation and mark only an actual delete. - The remote-download install accepted an unversioned response regardless of the handle's version, so during a rolling upgrade a delayed response could install stale content under a newer version. Require the response to be at least as new, with one exception: a handle still lacking local chunks takes the content anyway — it cannot read without it — but does not claim the response's log position. - Copy-event adoption returned without installing, so a foreign touch arriving before the copy's own event lost its timestamps. Content is unchanged either way, so the dirty pages stay valid; a clean handle now takes the entry, while a dirty one keeps its diverged version. * mount: one directory floor instead of a record per child; agree on TTL Review feedback: - Build completion wrote one KV record per direct child inside the cache write lock, so a large directory stalled every other cache operation for O(children) store writes. The directory's listing snapshot already covers every child it saw; make that floor the version for any child without a record of its own, and a child earns a record only when a later event touches it. One map write per build replaces the per-child writes, with the same fencing. - The presence probe read the store directly and so counted a TTL-expired entry as present, judging the path by a record describing content that has logically vanished. It now applies the same expiry the read path does, and an expired path falls back to its directory floor. - Preserve ErrNotFound identity when the commit-time re-read finds the object deleted, so callers still surface a 404. - Assert the rename-away source fence timestamp in the invalidation test. Also record the tombstone ceiling: distinct deleted names in a cached directory accumulate until it is rebuilt or evicted, which prunes everything at or below the new snapshot. * mount: pin the fence's clock domain instead of letting skew decide A log-position fence is stamped by one filer's clock under that filer's in-process lock, so comparing it to an event another filer logged is comparing two unrelated clocks. The two error directions are not equally costly: applying an event the fence already covered is a re-apply the base-equality check absorbs, while skipping one it does not cover leaves the handle holding exactly the state the event was meant to correct, with the subscription cursor already past it — the unhealable staleness this whole PR exists to remove. So refuse to guess. Fences now carry the signature of the filer that stamped them, and a handle records it alongside the position. An event is only fenced out when the filer that logged it is the one that stamped the fence — the logging filer appends its own signature, so its presence identifies the clock domain. Events from any other filer are applied. Positions taken from events keep comparing as before; the subscription already delivers those in order. The invalidation callback takes a struct now: it carries the path, entry, position, delete/rename distinction, and signatures, and was about to need a fifth positional parameter. * mount: follow a foreign rename; key page invalidation on content, not equality - A rename's old-path invalidation now carries the destination, and the handle follows the file there: an open fd tracks the inode, and leaving it on the old path made its next flush recreate that name instead of updating the renamed file. - Dirty pages overlay content, so only a content change invalidates them. Keying that on exact equality meant any timestamp-only event destroyed them, which the copy-adoption marker existed to paper over — a foreign touch could consume the marker and leave the copy's own event to drop the post-copy writes. Comparing content instead makes the marker unnecessary, so it is gone: a metadata-only event keeps the overlay, and a dirty handle keeps its diverged entry unless foreign content supersedes it. - A remote download response that is merely older is now refused even when the handle still lacks chunks; only an unversioned one is taken (and claims no position), since an older response's content predates what the handle reflects. - A refused or unversioned download no longer publishes to the metadata cache, where a zero-position event would clear the entry's version and let an older subscriber event roll the cache back. * mount: page invalidation keys on content alone; unversioned writes claim no position - sameEntryContent compared everything but timestamps, so a foreign chmod, chown, or xattr change counted as a content change and destroyed the dirty-page overlay. It was strict only to serve the copy-adoption marker, which is gone; its one caller now asks the question it actually needs — did the bytes change — so metadata-only events leave the overlay alone. - A rename over an existing file destroys that file, but its open handle was left live and still pointed at the name the renamed source now occupies, so its flush could overwrite it. MovePath already reports the displaced inode; mark that handle deleted. - An acknowledgment was refused whenever its position was numerically lower, even when a different filer stamped the fence it lost to. Two known, differing signatures mean unrelated clocks, so the comparison no longer applies there; unknown signatures still compare as before. - A local write with no log position behind it now records that explicitly instead of deleting its version record. Absence means the directory listing covers the path, which is why the snapshot floor applies; local content the listing never saw must not inherit it, or the events that would correct it are fenced out. * mount: widen the existing lookup functions instead of forking WithVersion twins The versioning work grew a parallel function for every accessor that needed to return a log position — lookupEntryWithVersion beside lookupEntry, maybeLoadEntryWithVersion beside maybeLoadEntry, FindEntryWithVersion beside FindEntry, AcquireFileHandleWithVersion beside AcquireFileHandle, advanceEntryVersion beside advanceEntryVersionTsNs, plus a getPbEntryWithVersion wrapper and an InsertListedEntriesForTest hook. Two names for one operation is two places to keep in step, and the split let callers pick the one that happened to compile. Each pair is now the single original name carrying the position, with callers that do not want it discarding it. filer_pb.GetEntry returns the fence its response already carried rather than a mount-side wrapper re-issuing the lookup, and InsertEntry takes the position its content reflects rather than a test-only twin that inserted without one. The one behavioural knot the merge exposed: AcquireFileHandle had been installing the entry on a pre-existing handle only in its unversioned form, which conflated 'the caller is authoritative' with 'the lookup had no version'. Deferred create is the only caller that means the former, so it now installs explicitly and the map function just acquires.
956 lines
33 KiB
Go
956 lines
33 KiB
Go
package s3api
|
|
|
|
import (
|
|
"context"
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/kms"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
|
)
|
|
|
|
// Compiled regex patterns for KMS key validation
|
|
var (
|
|
uuidRegex = regexp.MustCompile(`^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$`)
|
|
arnRegex = regexp.MustCompile(`^arn:aws:kms:[a-z0-9-]+:\d{12}:(key|alias)/.+$`)
|
|
)
|
|
|
|
// SSEKMSKey contains the metadata for an SSE-KMS encrypted object
|
|
type SSEKMSKey struct {
|
|
KeyID string // The KMS key ID used
|
|
EncryptedDataKey []byte // The encrypted data encryption key
|
|
EncryptionContext map[string]string // The encryption context used
|
|
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
|
|
type SSEKMSMetadata struct {
|
|
Algorithm string `json:"algorithm"` // "aws:kms"
|
|
KeyID string `json:"keyId"` // KMS key identifier
|
|
EncryptedDataKey string `json:"encryptedDataKey"` // Base64-encoded encrypted data key
|
|
EncryptionContext map[string]string `json:"encryptionContext"` // Encryption context
|
|
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 (
|
|
// Default data key size (256 bits)
|
|
DataKeySize = 32
|
|
)
|
|
|
|
// Bucket key cache TTL (moved to be used with per-bucket cache)
|
|
const BucketKeyCacheTTL = time.Hour
|
|
|
|
// CreateSSEKMSEncryptedReaderWithBucketKey creates an encrypted reader with optional S3 Bucket Keys optimization
|
|
func CreateSSEKMSEncryptedReaderWithBucketKey(r io.Reader, keyID string, encryptionContext map[string]string, bucketKeyEnabled bool) (io.Reader, *SSEKMSKey, error) {
|
|
if bucketKeyEnabled {
|
|
// Use S3 Bucket Keys optimization - try to get or create a bucket-level data key
|
|
// Note: This is a simplified implementation. In practice, this would need
|
|
// access to the bucket name and S3ApiServer instance for proper per-bucket caching.
|
|
// For now, generate per-object keys (bucket key optimization disabled)
|
|
glog.V(2).Infof("Bucket key optimization requested but not fully implemented yet - using per-object keys")
|
|
bucketKeyEnabled = false
|
|
}
|
|
|
|
// Generate data key using common utility
|
|
dataKeyResult, err := generateKMSDataKey(keyID, encryptionContext)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
// Ensure we clear the plaintext data key from memory when done
|
|
defer clearKMSDataKey(dataKeyResult)
|
|
|
|
// Generate a random IV for CTR mode
|
|
// Note: AES-CTR is used for object data encryption (not AES-GCM) because:
|
|
// 1. CTR mode supports streaming encryption for large objects
|
|
// 2. CTR mode supports range requests (seek to arbitrary positions)
|
|
// 3. This matches AWS S3 and other S3-compatible implementations
|
|
// The KMS data key encryption (separate layer) uses AES-GCM for authentication
|
|
iv := make([]byte, s3_constants.AESBlockSize)
|
|
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
|
return nil, nil, fmt.Errorf("failed to generate IV: %v", err)
|
|
}
|
|
|
|
// Create CTR mode cipher stream
|
|
stream := cipher.NewCTR(dataKeyResult.Block, iv)
|
|
|
|
// 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}
|
|
|
|
return encryptedReader, sseKey, nil
|
|
}
|
|
|
|
// CreateSSEKMSEncryptedReaderWithBaseIVAndOffset creates an SSE-KMS encrypted reader using a provided base IV and offset
|
|
// This is used for multipart uploads where all chunks need unique IVs to prevent IV reuse vulnerabilities
|
|
func CreateSSEKMSEncryptedReaderWithBaseIVAndOffset(r io.Reader, keyID string, encryptionContext map[string]string, bucketKeyEnabled bool, baseIV []byte, offset int64) (io.Reader, *SSEKMSKey, error) {
|
|
if err := ValidateIV(baseIV, "base IV"); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
// Generate data key using common utility
|
|
dataKeyResult, err := generateKMSDataKey(keyID, encryptionContext)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
// 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).
|
|
iv, _ := calculateIVWithOffset(baseIV, offset)
|
|
|
|
// Create CTR mode cipher stream
|
|
stream := cipher.NewCTR(dataKeyResult.Block, iv)
|
|
|
|
// 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
|
|
encryptedReader := &cipher.StreamReader{S: stream, R: r}
|
|
|
|
return encryptedReader, sseKey, nil
|
|
}
|
|
|
|
// hashEncryptionContext creates a deterministic hash of the encryption context
|
|
func hashEncryptionContext(encryptionContext map[string]string) string {
|
|
if len(encryptionContext) == 0 {
|
|
return "empty"
|
|
}
|
|
|
|
// Create a deterministic representation of the context
|
|
hash := sha256.New()
|
|
|
|
// Sort keys to ensure deterministic hash
|
|
keys := make([]string, 0, len(encryptionContext))
|
|
for k := range encryptionContext {
|
|
keys = append(keys, k)
|
|
}
|
|
|
|
sort.Strings(keys)
|
|
|
|
// Hash the sorted key-value pairs
|
|
for _, k := range keys {
|
|
hash.Write([]byte(k))
|
|
hash.Write([]byte("="))
|
|
hash.Write([]byte(encryptionContext[k]))
|
|
hash.Write([]byte(";"))
|
|
}
|
|
|
|
return hex.EncodeToString(hash.Sum(nil))[:16] // Use first 16 chars for brevity
|
|
}
|
|
|
|
// getBucketDataKey retrieves or creates a cached bucket-level data key for SSE-KMS
|
|
// This is a simplified implementation that demonstrates the per-bucket caching concept
|
|
// In a full implementation, this would integrate with the actual bucket configuration system
|
|
func getBucketDataKey(bucketName, keyID string, encryptionContext map[string]string, bucketCache *BucketKMSCache) (*kms.GenerateDataKeyResponse, error) {
|
|
// Create context hash for cache key
|
|
contextHash := hashEncryptionContext(encryptionContext)
|
|
cacheKey := fmt.Sprintf("%s:%s", keyID, contextHash)
|
|
|
|
// Try to get from cache first if cache is available
|
|
if bucketCache != nil {
|
|
if cacheEntry, found := bucketCache.Get(cacheKey); found {
|
|
if dataKey, ok := cacheEntry.DataKey.(*kms.GenerateDataKeyResponse); ok {
|
|
glog.V(3).Infof("Using cached bucket key for bucket %s, keyID %s", bucketName, keyID)
|
|
return dataKey, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
// Cache miss - generate new data key
|
|
kmsProvider := kms.GetGlobalKMS()
|
|
if kmsProvider == nil {
|
|
return nil, fmt.Errorf("KMS is not configured")
|
|
}
|
|
|
|
dataKeyReq := &kms.GenerateDataKeyRequest{
|
|
KeyID: keyID,
|
|
KeySpec: kms.KeySpecAES256,
|
|
EncryptionContext: encryptionContext,
|
|
}
|
|
|
|
ctx := context.Background()
|
|
dataKeyResp, err := kmsProvider.GenerateDataKey(ctx, dataKeyReq)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to generate bucket data key: %v", err)
|
|
}
|
|
|
|
// Cache the data key for future use if cache is available
|
|
if bucketCache != nil {
|
|
bucketCache.Set(cacheKey, keyID, dataKeyResp, BucketKeyCacheTTL)
|
|
glog.V(2).Infof("Generated and cached new bucket key for bucket %s, keyID %s", bucketName, keyID)
|
|
} else {
|
|
glog.V(2).Infof("Generated new bucket key for bucket %s, keyID %s (caching disabled)", bucketName, keyID)
|
|
}
|
|
|
|
return dataKeyResp, nil
|
|
}
|
|
|
|
// CreateSSEKMSEncryptedReaderForBucket creates an encrypted reader with bucket-specific caching
|
|
// This method is part of S3ApiServer to access bucket configuration and caching
|
|
func (s3a *S3ApiServer) CreateSSEKMSEncryptedReaderForBucket(r io.Reader, bucketName, keyID string, encryptionContext map[string]string, bucketKeyEnabled bool) (io.Reader, *SSEKMSKey, error) {
|
|
var dataKeyResp *kms.GenerateDataKeyResponse
|
|
var err error
|
|
|
|
if bucketKeyEnabled {
|
|
// Use S3 Bucket Keys optimization with persistent per-bucket caching
|
|
bucketCache, err := s3a.getBucketKMSCache(bucketName)
|
|
if err != nil {
|
|
glog.V(2).Infof("Failed to get bucket KMS cache for %s, falling back to per-object key: %v", bucketName, err)
|
|
bucketKeyEnabled = false
|
|
} else {
|
|
dataKeyResp, err = getBucketDataKey(bucketName, keyID, encryptionContext, bucketCache)
|
|
if err != nil {
|
|
// Fall back to per-object key generation if bucket key fails
|
|
glog.V(2).Infof("Bucket key generation failed for bucket %s, falling back to per-object key: %v", bucketName, err)
|
|
bucketKeyEnabled = false
|
|
}
|
|
}
|
|
}
|
|
|
|
if !bucketKeyEnabled {
|
|
// Generate a per-object data encryption key using KMS
|
|
kmsProvider := kms.GetGlobalKMS()
|
|
if kmsProvider == nil {
|
|
return nil, nil, fmt.Errorf("KMS is not configured")
|
|
}
|
|
|
|
dataKeyReq := &kms.GenerateDataKeyRequest{
|
|
KeyID: keyID,
|
|
KeySpec: kms.KeySpecAES256,
|
|
EncryptionContext: encryptionContext,
|
|
}
|
|
|
|
ctx := context.Background()
|
|
dataKeyResp, err = kmsProvider.GenerateDataKey(ctx, dataKeyReq)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("failed to generate data key: %v", err)
|
|
}
|
|
}
|
|
|
|
// Ensure we clear the plaintext data key from memory when done
|
|
defer kms.ClearSensitiveData(dataKeyResp.Plaintext)
|
|
|
|
// Create AES cipher with the data key
|
|
block, err := aes.NewCipher(dataKeyResp.Plaintext)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("failed to create AES cipher: %v", err)
|
|
}
|
|
|
|
// Generate a random IV for CTR mode
|
|
iv := make([]byte, 16) // AES block size
|
|
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
|
return nil, nil, fmt.Errorf("failed to generate IV: %v", err)
|
|
}
|
|
|
|
// Create CTR mode cipher stream
|
|
stream := cipher.NewCTR(block, iv)
|
|
|
|
// 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: 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
|
|
}
|
|
|
|
// getBucketKMSCache gets or creates the persistent KMS cache for a bucket
|
|
func (s3a *S3ApiServer) getBucketKMSCache(bucketName string) (*BucketKMSCache, error) {
|
|
// Get bucket configuration
|
|
bucketConfig, errCode := s3a.getBucketConfig(bucketName)
|
|
if errCode != s3err.ErrNone {
|
|
if errCode == s3err.ErrNoSuchBucket {
|
|
return nil, fmt.Errorf("bucket %s does not exist", bucketName)
|
|
}
|
|
return nil, fmt.Errorf("failed to get bucket config: %v", errCode)
|
|
}
|
|
|
|
// Initialize KMS cache if it doesn't exist
|
|
if bucketConfig.KMSKeyCache == nil {
|
|
bucketConfig.KMSKeyCache = NewBucketKMSCache(bucketName, BucketKeyCacheTTL)
|
|
glog.V(3).Infof("Initialized new KMS cache for bucket %s", bucketName)
|
|
}
|
|
|
|
return bucketConfig.KMSKeyCache, nil
|
|
}
|
|
|
|
// CleanupBucketKMSCache performs cleanup of expired KMS keys for a specific bucket
|
|
func (s3a *S3ApiServer) CleanupBucketKMSCache(bucketName string) int {
|
|
bucketCache, err := s3a.getBucketKMSCache(bucketName)
|
|
if err != nil {
|
|
glog.V(3).Infof("Could not get KMS cache for bucket %s: %v", bucketName, err)
|
|
return 0
|
|
}
|
|
|
|
cleaned := bucketCache.CleanupExpired()
|
|
if cleaned > 0 {
|
|
glog.V(2).Infof("Cleaned up %d expired KMS keys for bucket %s", cleaned, bucketName)
|
|
}
|
|
return cleaned
|
|
}
|
|
|
|
// CleanupAllBucketKMSCaches performs cleanup of expired KMS keys for all buckets
|
|
func (s3a *S3ApiServer) CleanupAllBucketKMSCaches() int {
|
|
totalCleaned := 0
|
|
|
|
if s3a.bucketConfigCache != nil {
|
|
// Clean up each cached bucket's KMS cache
|
|
for _, bucketName := range s3a.bucketConfigCache.cache.Keys() {
|
|
cleaned := s3a.CleanupBucketKMSCache(bucketName)
|
|
totalCleaned += cleaned
|
|
}
|
|
}
|
|
|
|
if totalCleaned > 0 {
|
|
glog.V(2).Infof("Cleaned up %d expired KMS keys across %d bucket caches", totalCleaned, s3a.bucketConfigCache.cache.Len())
|
|
}
|
|
return totalCleaned
|
|
}
|
|
|
|
// CreateSSEKMSDecryptedReader creates a decrypted reader using KMS envelope encryption
|
|
func CreateSSEKMSDecryptedReader(r io.Reader, sseKey *SSEKMSKey) (io.Reader, error) {
|
|
kmsProvider := kms.GetGlobalKMS()
|
|
if kmsProvider == nil {
|
|
return nil, fmt.Errorf("KMS is not configured")
|
|
}
|
|
|
|
// Decrypt the data encryption key using KMS
|
|
decryptReq := &kms.DecryptRequest{
|
|
CiphertextBlob: sseKey.EncryptedDataKey,
|
|
EncryptionContext: sseKey.EncryptionContext,
|
|
}
|
|
|
|
ctx := context.Background()
|
|
decryptResp, err := kmsProvider.Decrypt(ctx, decryptReq)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to decrypt data key: %v", err)
|
|
}
|
|
|
|
// Ensure we clear the plaintext data key from memory when done
|
|
defer kms.ClearSensitiveData(decryptResp.Plaintext)
|
|
|
|
// Verify the key ID matches (security check)
|
|
if decryptResp.KeyID != sseKey.KeyID {
|
|
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)
|
|
}
|
|
|
|
// Calculate the correct IV for this chunk's offset within the original part
|
|
// Note: The skip bytes must be discarded by the caller before reading from the returned reader
|
|
var iv []byte
|
|
if sseKey.ChunkOffset > 0 {
|
|
iv, _ = calculateIVWithOffset(sseKey.IV, sseKey.ChunkOffset)
|
|
// Skip value is ignored here; caller must handle intra-block byte skipping
|
|
} else {
|
|
iv = sseKey.IV
|
|
}
|
|
|
|
// Create AES cipher with the decrypted data key
|
|
block, err := aes.NewCipher(decryptResp.Plaintext)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create AES cipher: %v", err)
|
|
}
|
|
|
|
// Create CTR mode cipher stream for decryption
|
|
// Note: AES-CTR is used for object data decryption to match the encryption mode
|
|
stream := cipher.NewCTR(block, iv)
|
|
decryptReader := &cipher.StreamReader{S: stream, R: r}
|
|
|
|
// Wrap with closer if the underlying reader implements io.Closer
|
|
if closer, ok := r.(io.Closer); ok {
|
|
return &decryptReaderCloser{
|
|
Reader: decryptReader,
|
|
underlyingCloser: closer,
|
|
}, nil
|
|
}
|
|
|
|
// Return the decrypted reader
|
|
return decryptReader, nil
|
|
}
|
|
|
|
// BuildEncryptionContext creates the encryption context for S3 objects
|
|
func BuildEncryptionContext(bucketName, objectKey string, useBucketKey bool) map[string]string {
|
|
return kms.BuildS3EncryptionContext(bucketName, objectKey, useBucketKey)
|
|
}
|
|
|
|
// parseEncryptionContext parses the user-provided encryption context from base64 JSON
|
|
func parseEncryptionContext(contextHeader string) (map[string]string, error) {
|
|
if contextHeader == "" {
|
|
return nil, nil
|
|
}
|
|
|
|
// Decode base64
|
|
contextBytes, err := base64.StdEncoding.DecodeString(contextHeader)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid base64 encoding in encryption context: %w", err)
|
|
}
|
|
|
|
// Parse JSON
|
|
var context map[string]string
|
|
if err := json.Unmarshal(contextBytes, &context); err != nil {
|
|
return nil, fmt.Errorf("invalid JSON in encryption context: %w", err)
|
|
}
|
|
|
|
// Validate context keys and values
|
|
for k, v := range context {
|
|
if k == "" || v == "" {
|
|
return nil, fmt.Errorf("encryption context keys and values cannot be empty")
|
|
}
|
|
// AWS KMS has limits on context key/value length (256 chars each)
|
|
if len(k) > 256 || len(v) > 256 {
|
|
return nil, fmt.Errorf("encryption context key or value too long (max 256 characters)")
|
|
}
|
|
}
|
|
|
|
return context, nil
|
|
}
|
|
|
|
// SerializeSSEKMSMetadata serializes SSE-KMS metadata for storage in object metadata
|
|
func SerializeSSEKMSMetadata(sseKey *SSEKMSKey) ([]byte, error) {
|
|
if err := ValidateSSEKMSKey(sseKey); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
metadata := &SSEKMSMetadata{
|
|
Algorithm: s3_constants.SSEAlgorithmKMS,
|
|
KeyID: sseKey.KeyID,
|
|
EncryptedDataKey: base64.StdEncoding.EncodeToString(sseKey.EncryptedDataKey),
|
|
EncryptionContext: sseKey.EncryptionContext,
|
|
BucketKeyEnabled: sseKey.BucketKeyEnabled,
|
|
IV: base64.StdEncoding.EncodeToString(sseKey.IV), // Store IV for decryption
|
|
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)
|
|
}
|
|
|
|
glog.V(4).Infof("Serialized SSE-KMS metadata: keyID=%s, bucketKey=%t", sseKey.KeyID, sseKey.BucketKeyEnabled)
|
|
return data, nil
|
|
}
|
|
|
|
// DeserializeSSEKMSMetadata deserializes SSE-KMS metadata from storage and reconstructs the SSE-KMS key
|
|
func DeserializeSSEKMSMetadata(data []byte) (*SSEKMSKey, error) {
|
|
if len(data) == 0 {
|
|
return nil, fmt.Errorf("empty SSE-KMS metadata")
|
|
}
|
|
|
|
var metadata SSEKMSMetadata
|
|
if err := json.Unmarshal(data, &metadata); err != nil {
|
|
return nil, fmt.Errorf("failed to unmarshal SSE-KMS metadata: %w", err)
|
|
}
|
|
|
|
// Validate algorithm - be lenient with missing/empty algorithm for backward compatibility
|
|
if metadata.Algorithm != "" && metadata.Algorithm != s3_constants.SSEAlgorithmKMS {
|
|
return nil, fmt.Errorf("invalid SSE-KMS algorithm: %s", metadata.Algorithm)
|
|
}
|
|
|
|
// Set default algorithm if empty
|
|
if metadata.Algorithm == "" {
|
|
metadata.Algorithm = s3_constants.SSEAlgorithmKMS
|
|
}
|
|
|
|
// Decode the encrypted data key
|
|
encryptedDataKey, err := base64.StdEncoding.DecodeString(metadata.EncryptedDataKey)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to decode encrypted data key: %w", err)
|
|
}
|
|
|
|
// Decode the IV
|
|
var iv []byte
|
|
if metadata.IV != "" {
|
|
iv, err = base64.StdEncoding.DecodeString(metadata.IV)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to decode IV: %w", err)
|
|
}
|
|
}
|
|
|
|
// 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,
|
|
EncryptionContext: metadata.EncryptionContext,
|
|
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)
|
|
return sseKey, nil
|
|
}
|
|
|
|
// SSECMetadata represents SSE-C metadata for per-chunk storage (unified with SSE-KMS approach)
|
|
type SSECMetadata struct {
|
|
Algorithm string `json:"algorithm"` // SSE-C algorithm (always "AES256")
|
|
IV string `json:"iv"` // Base64-encoded initialization vector for this chunk
|
|
KeyMD5 string `json:"keyMD5"` // MD5 of the customer-provided key
|
|
PartOffset int64 `json:"partOffset"` // Offset within original multipart part (for IV calculation)
|
|
}
|
|
|
|
// SerializeSSECMetadata serializes SSE-C metadata for storage in chunk metadata
|
|
func SerializeSSECMetadata(iv []byte, keyMD5 string, partOffset int64) ([]byte, error) {
|
|
if err := ValidateIV(iv, "IV"); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
metadata := &SSECMetadata{
|
|
Algorithm: s3_constants.SSEAlgorithmAES256,
|
|
IV: base64.StdEncoding.EncodeToString(iv),
|
|
KeyMD5: keyMD5,
|
|
PartOffset: partOffset,
|
|
}
|
|
|
|
data, err := json.Marshal(metadata)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to marshal SSE-C metadata: %w", err)
|
|
}
|
|
|
|
glog.V(4).Infof("Serialized SSE-C metadata: keyMD5=%s, partOffset=%d", keyMD5, partOffset)
|
|
return data, nil
|
|
}
|
|
|
|
// DeserializeSSECMetadata deserializes SSE-C metadata from chunk storage
|
|
func DeserializeSSECMetadata(data []byte) (*SSECMetadata, error) {
|
|
if len(data) == 0 {
|
|
return nil, fmt.Errorf("empty SSE-C metadata")
|
|
}
|
|
|
|
var metadata SSECMetadata
|
|
if err := json.Unmarshal(data, &metadata); err != nil {
|
|
return nil, fmt.Errorf("failed to unmarshal SSE-C metadata: %w", err)
|
|
}
|
|
|
|
// Validate algorithm
|
|
if metadata.Algorithm != s3_constants.SSEAlgorithmAES256 {
|
|
return nil, fmt.Errorf("invalid SSE-C algorithm: %s", metadata.Algorithm)
|
|
}
|
|
|
|
// Validate IV
|
|
if metadata.IV == "" {
|
|
return nil, fmt.Errorf("missing IV in SSE-C metadata")
|
|
}
|
|
|
|
if _, err := base64.StdEncoding.DecodeString(metadata.IV); err != nil {
|
|
return nil, fmt.Errorf("invalid base64 IV in SSE-C metadata: %w", err)
|
|
}
|
|
|
|
glog.V(4).Infof("Deserialized SSE-C metadata: keyMD5=%s, partOffset=%d", metadata.KeyMD5, metadata.PartOffset)
|
|
return &metadata, nil
|
|
}
|
|
|
|
// AddSSEKMSResponseHeaders adds SSE-KMS response headers to an HTTP response
|
|
func AddSSEKMSResponseHeaders(w http.ResponseWriter, sseKey *SSEKMSKey) {
|
|
w.Header().Set(s3_constants.AmzServerSideEncryption, s3_constants.SSEAlgorithmKMS)
|
|
w.Header().Set(s3_constants.AmzServerSideEncryptionAwsKmsKeyId, sseKey.KeyID)
|
|
|
|
if len(sseKey.EncryptionContext) > 0 {
|
|
// Encode encryption context as base64 JSON
|
|
contextBytes, err := json.Marshal(sseKey.EncryptionContext)
|
|
if err == nil {
|
|
contextB64 := base64.StdEncoding.EncodeToString(contextBytes)
|
|
w.Header().Set(s3_constants.AmzServerSideEncryptionContext, contextB64)
|
|
} else {
|
|
glog.Errorf("Failed to encode encryption context: %v", err)
|
|
}
|
|
}
|
|
|
|
if sseKey.BucketKeyEnabled {
|
|
w.Header().Set(s3_constants.AmzServerSideEncryptionBucketKeyEnabled, "true")
|
|
}
|
|
}
|
|
|
|
// IsSSEKMSRequest checks if the request contains SSE-KMS headers
|
|
func IsSSEKMSRequest(r *http.Request) bool {
|
|
// If SSE-C headers are present, this is not an SSE-KMS request (they are mutually exclusive)
|
|
if r.Header.Get(s3_constants.AmzServerSideEncryptionCustomerAlgorithm) != "" {
|
|
return false
|
|
}
|
|
|
|
// According to AWS S3 specification, SSE-KMS is only valid when the encryption header
|
|
// is explicitly set to "aws:kms". The KMS key ID header alone is not sufficient.
|
|
sseAlgorithm := r.Header.Get(s3_constants.AmzServerSideEncryption)
|
|
return sseAlgorithm == s3_constants.SSEAlgorithmKMS
|
|
}
|
|
|
|
// IsSSEKMSEncrypted checks if the metadata indicates SSE-KMS encryption
|
|
func IsSSEKMSEncrypted(metadata map[string][]byte) bool {
|
|
if metadata == nil {
|
|
return false
|
|
}
|
|
|
|
// The canonical way to identify an SSE-KMS encrypted object is by this header.
|
|
if sseAlgorithm, exists := metadata[s3_constants.AmzServerSideEncryption]; exists {
|
|
return string(sseAlgorithm) == s3_constants.SSEAlgorithmKMS
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// MapKMSErrorToS3Error maps KMS errors to appropriate S3 error codes
|
|
func MapKMSErrorToS3Error(err error) s3err.ErrorCode {
|
|
if err == nil {
|
|
return s3err.ErrNone
|
|
}
|
|
|
|
// Check if it's a KMS error
|
|
kmsErr, ok := err.(*kms.KMSError)
|
|
if !ok {
|
|
return s3err.ErrInternalError
|
|
}
|
|
|
|
switch kmsErr.Code {
|
|
case kms.ErrCodeNotFoundException:
|
|
return s3err.ErrKMSKeyNotFound
|
|
case kms.ErrCodeAccessDenied:
|
|
return s3err.ErrKMSAccessDenied
|
|
case kms.ErrCodeKeyUnavailable:
|
|
return s3err.ErrKMSDisabled
|
|
case kms.ErrCodeInvalidKeyUsage:
|
|
return s3err.ErrKMSAccessDenied
|
|
case kms.ErrCodeInvalidCiphertext:
|
|
return s3err.ErrKMSInvalidCiphertext
|
|
default:
|
|
glog.Errorf("Unmapped KMS error: %s - %s", kmsErr.Code, kmsErr.Message)
|
|
return s3err.ErrInternalError
|
|
}
|
|
}
|
|
|
|
// SSEKMSCopyStrategy represents different strategies for copying SSE-KMS encrypted objects
|
|
type SSEKMSCopyStrategy int
|
|
|
|
const (
|
|
// SSEKMSCopyStrategyDirect - Direct chunk copy (same key, no re-encryption needed)
|
|
SSEKMSCopyStrategyDirect SSEKMSCopyStrategy = iota
|
|
// SSEKMSCopyStrategyDecryptEncrypt - Decrypt source and re-encrypt for destination
|
|
SSEKMSCopyStrategyDecryptEncrypt
|
|
)
|
|
|
|
// String returns string representation of the strategy
|
|
func (s SSEKMSCopyStrategy) String() string {
|
|
switch s {
|
|
case SSEKMSCopyStrategyDirect:
|
|
return "Direct"
|
|
case SSEKMSCopyStrategyDecryptEncrypt:
|
|
return "DecryptEncrypt"
|
|
default:
|
|
return "Unknown"
|
|
}
|
|
}
|
|
|
|
// GetSourceSSEKMSInfo extracts SSE-KMS information from source object metadata
|
|
func GetSourceSSEKMSInfo(metadata map[string][]byte) (keyID string, isEncrypted bool) {
|
|
if sseAlgorithm, exists := metadata[s3_constants.AmzServerSideEncryption]; exists && string(sseAlgorithm) == s3_constants.SSEAlgorithmKMS {
|
|
if kmsKeyID, exists := metadata[s3_constants.AmzServerSideEncryptionAwsKmsKeyId]; exists {
|
|
return string(kmsKeyID), true
|
|
}
|
|
return "", true // SSE-KMS with default key
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
// CanDirectCopySSEKMS determines if we can directly copy chunks without decrypt/re-encrypt
|
|
func CanDirectCopySSEKMS(srcMetadata map[string][]byte, destKeyID string) bool {
|
|
srcKeyID, srcEncrypted := GetSourceSSEKMSInfo(srcMetadata)
|
|
|
|
// Case 1: Source unencrypted, destination unencrypted -> Direct copy
|
|
if !srcEncrypted && destKeyID == "" {
|
|
return true
|
|
}
|
|
|
|
// Case 2: Source encrypted with same KMS key as destination -> Direct copy
|
|
if srcEncrypted && destKeyID != "" {
|
|
// Same key if key IDs match (empty means default key)
|
|
return srcKeyID == destKeyID
|
|
}
|
|
|
|
// All other cases require decrypt/re-encrypt
|
|
return false
|
|
}
|
|
|
|
// DetermineSSEKMSCopyStrategy determines the optimal copy strategy for SSE-KMS
|
|
func DetermineSSEKMSCopyStrategy(srcMetadata map[string][]byte, destKeyID string) (SSEKMSCopyStrategy, error) {
|
|
if CanDirectCopySSEKMS(srcMetadata, destKeyID) {
|
|
return SSEKMSCopyStrategyDirect, nil
|
|
}
|
|
return SSEKMSCopyStrategyDecryptEncrypt, nil
|
|
}
|
|
|
|
// ParseSSEKMSCopyHeaders parses SSE-KMS headers from copy request
|
|
func ParseSSEKMSCopyHeaders(r *http.Request) (destKeyID string, encryptionContext map[string]string, bucketKeyEnabled bool, err error) {
|
|
// Check if this is an SSE-KMS request
|
|
if !IsSSEKMSRequest(r) {
|
|
return "", nil, false, nil
|
|
}
|
|
|
|
// Get destination KMS key ID
|
|
destKeyID = r.Header.Get(s3_constants.AmzServerSideEncryptionAwsKmsKeyId)
|
|
|
|
// Validate key ID if provided
|
|
if destKeyID != "" && !isValidKMSKeyID(destKeyID) {
|
|
return "", nil, false, fmt.Errorf("invalid KMS key ID: %s", destKeyID)
|
|
}
|
|
|
|
// Parse encryption context if provided
|
|
if contextHeader := r.Header.Get(s3_constants.AmzServerSideEncryptionContext); contextHeader != "" {
|
|
contextBytes, decodeErr := base64.StdEncoding.DecodeString(contextHeader)
|
|
if decodeErr != nil {
|
|
return "", nil, false, fmt.Errorf("invalid encryption context encoding: %v", decodeErr)
|
|
}
|
|
|
|
if unmarshalErr := json.Unmarshal(contextBytes, &encryptionContext); unmarshalErr != nil {
|
|
return "", nil, false, fmt.Errorf("invalid encryption context JSON: %v", unmarshalErr)
|
|
}
|
|
}
|
|
|
|
// Parse bucket key enabled flag
|
|
if bucketKeyHeader := r.Header.Get(s3_constants.AmzServerSideEncryptionBucketKeyEnabled); bucketKeyHeader != "" {
|
|
bucketKeyEnabled = strings.ToLower(bucketKeyHeader) == "true"
|
|
}
|
|
|
|
return destKeyID, encryptionContext, bucketKeyEnabled, nil
|
|
}
|
|
|
|
// UnifiedCopyStrategy represents all possible copy strategies across encryption types
|
|
type UnifiedCopyStrategy int
|
|
|
|
const (
|
|
// CopyStrategyDirect - Direct chunk copy (no encryption changes)
|
|
CopyStrategyDirect UnifiedCopyStrategy = iota
|
|
// CopyStrategyEncrypt - Encrypt during copy (plain → encrypted)
|
|
CopyStrategyEncrypt
|
|
// CopyStrategyDecrypt - Decrypt during copy (encrypted → plain)
|
|
CopyStrategyDecrypt
|
|
// CopyStrategyReencrypt - Decrypt and re-encrypt (different keys/methods)
|
|
CopyStrategyReencrypt
|
|
// CopyStrategyKeyRotation - Same object, different key (metadata-only update)
|
|
CopyStrategyKeyRotation
|
|
)
|
|
|
|
// String returns string representation of the unified strategy
|
|
func (s UnifiedCopyStrategy) String() string {
|
|
switch s {
|
|
case CopyStrategyDirect:
|
|
return "Direct"
|
|
case CopyStrategyEncrypt:
|
|
return "Encrypt"
|
|
case CopyStrategyDecrypt:
|
|
return "Decrypt"
|
|
case CopyStrategyReencrypt:
|
|
return "Reencrypt"
|
|
case CopyStrategyKeyRotation:
|
|
return "KeyRotation"
|
|
default:
|
|
return "Unknown"
|
|
}
|
|
}
|
|
|
|
// EncryptionState represents the encryption state of source and destination
|
|
type EncryptionState struct {
|
|
SrcSSEC bool
|
|
SrcSSEKMS bool
|
|
SrcSSES3 bool
|
|
DstSSEC bool
|
|
DstSSEKMS bool
|
|
DstSSES3 bool
|
|
SameObject bool
|
|
}
|
|
|
|
// IsSourceEncrypted returns true if source has any encryption
|
|
func (e *EncryptionState) IsSourceEncrypted() bool {
|
|
return e.SrcSSEC || e.SrcSSEKMS || e.SrcSSES3
|
|
}
|
|
|
|
// IsTargetEncrypted returns true if target should be encrypted
|
|
func (e *EncryptionState) IsTargetEncrypted() bool {
|
|
return e.DstSSEC || e.DstSSEKMS || e.DstSSES3
|
|
}
|
|
|
|
// DetermineUnifiedCopyStrategy determines the optimal copy strategy for all encryption types
|
|
func DetermineUnifiedCopyStrategy(state *EncryptionState, srcMetadata map[string][]byte, r *http.Request) (UnifiedCopyStrategy, error) {
|
|
// Key rotation: same object with different encryption
|
|
if state.SameObject && state.IsSourceEncrypted() && state.IsTargetEncrypted() {
|
|
// Check if it's actually a key change
|
|
if state.SrcSSEC && state.DstSSEC {
|
|
// SSE-C key rotation - need to compare keys
|
|
return CopyStrategyKeyRotation, nil
|
|
}
|
|
if state.SrcSSEKMS && state.DstSSEKMS {
|
|
// SSE-KMS key rotation - need to compare key IDs
|
|
srcKeyID, _ := GetSourceSSEKMSInfo(srcMetadata)
|
|
dstKeyID := r.Header.Get(s3_constants.AmzServerSideEncryptionAwsKmsKeyId)
|
|
if srcKeyID != dstKeyID {
|
|
return CopyStrategyKeyRotation, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
// Direct copy: no encryption changes
|
|
if !state.IsSourceEncrypted() && !state.IsTargetEncrypted() {
|
|
return CopyStrategyDirect, nil
|
|
}
|
|
|
|
// Same encryption type and key
|
|
if state.SrcSSEKMS && state.DstSSEKMS {
|
|
srcKeyID, _ := GetSourceSSEKMSInfo(srcMetadata)
|
|
dstKeyID := r.Header.Get(s3_constants.AmzServerSideEncryptionAwsKmsKeyId)
|
|
if srcKeyID == dstKeyID {
|
|
return CopyStrategyDirect, nil
|
|
}
|
|
}
|
|
|
|
if state.SrcSSEC && state.DstSSEC {
|
|
// For SSE-C, we'd need to compare the actual keys, but we can't do that securely
|
|
// So we assume different keys and use reencrypt strategy
|
|
return CopyStrategyReencrypt, nil
|
|
}
|
|
|
|
// Encrypt: plain → encrypted
|
|
if !state.IsSourceEncrypted() && state.IsTargetEncrypted() {
|
|
return CopyStrategyEncrypt, nil
|
|
}
|
|
|
|
// Decrypt: encrypted → plain
|
|
if state.IsSourceEncrypted() && !state.IsTargetEncrypted() {
|
|
return CopyStrategyDecrypt, nil
|
|
}
|
|
|
|
// Reencrypt: different encryption types or keys
|
|
if state.IsSourceEncrypted() && state.IsTargetEncrypted() {
|
|
return CopyStrategyReencrypt, nil
|
|
}
|
|
|
|
return CopyStrategyDirect, nil
|
|
}
|
|
|
|
// DetectEncryptionStateWithEntry analyzes the source entry and request headers to determine encryption state
|
|
// This version can detect multipart encrypted objects by examining chunks
|
|
func DetectEncryptionStateWithEntry(entry *filer_pb.Entry, r *http.Request, srcPath, dstPath string) *EncryptionState {
|
|
state := &EncryptionState{
|
|
SrcSSEC: IsSSECEncryptedWithEntry(entry),
|
|
SrcSSEKMS: IsSSEKMSEncryptedWithEntry(entry),
|
|
SrcSSES3: IsSSES3EncryptedInternal(entry.Extended),
|
|
DstSSEC: IsSSECRequest(r),
|
|
DstSSEKMS: IsSSEKMSRequest(r),
|
|
DstSSES3: IsSSES3RequestInternal(r),
|
|
SameObject: srcPath == dstPath,
|
|
}
|
|
|
|
return state
|
|
}
|
|
|
|
// IsSSEKMSEncryptedWithEntry detects SSE-KMS encryption from entry (including multipart objects)
|
|
func IsSSEKMSEncryptedWithEntry(entry *filer_pb.Entry) bool {
|
|
if entry == nil {
|
|
return false
|
|
}
|
|
|
|
// Check object-level metadata first
|
|
if IsSSEKMSEncrypted(entry.Extended) {
|
|
return true
|
|
}
|
|
|
|
// Check for multipart SSE-KMS by examining chunks
|
|
if len(entry.GetChunks()) > 0 {
|
|
for _, chunk := range entry.GetChunks() {
|
|
if chunk.GetSseType() == filer_pb.SSEType_SSE_KMS {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// IsSSECEncryptedWithEntry detects SSE-C encryption from entry (including multipart objects)
|
|
func IsSSECEncryptedWithEntry(entry *filer_pb.Entry) bool {
|
|
if entry == nil {
|
|
return false
|
|
}
|
|
|
|
// Check object-level metadata first
|
|
if IsSSECEncrypted(entry.Extended) {
|
|
return true
|
|
}
|
|
|
|
// Check for multipart SSE-C by examining chunks
|
|
if len(entry.GetChunks()) > 0 {
|
|
for _, chunk := range entry.GetChunks() {
|
|
if chunk.GetSseType() == filer_pb.SSEType_SSE_C {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// Helper functions for SSE-C detection are in s3_sse_c.go
|