Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ See [docs/architecture.md](docs/architecture.md) for detailed architecture docum

### Tiered Store Mode

In tiered mode, validated plain-object PUTs no larger than `cache.size_threshold` are stored locally, and their metadata is authoritative. A background re-tier started by a GET is bound to the marker version seen by that GET, so it cannot replace metadata committed by a later write. See [docs/tiered-mode.md](docs/tiered-mode.md) for the full behavior.
In tiered mode, validated plain-object PUTs no larger than `cache.size_threshold` are stored locally, and their metadata is authoritative. PUT preconditions follow the prior tier even when a larger replacement moves the body upstream: TAG checks a local prior itself and leaves upstream-tier conditions to upstream. A background re-tier started by a GET is bound to the marker version seen by that GET, so it cannot replace metadata committed by a later write. See [docs/tiered-mode.md](docs/tiered-mode.md) for the full behavior.

## Performance

Expand Down
13 changes: 13 additions & 0 deletions auth/chunk_verifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"crypto/hmac"
"encoding/hex"
"errors"
"strings"
)

// ErrChunkSignatureMismatch is returned when a chunk of a
Expand Down Expand Up @@ -44,3 +45,15 @@ func (c *ChunkVerifier) VerifyChunk(signature string, chunkSHA256 []byte) error
c.previous = expected
return nil
}

// VerifyTrailer authenticates the canonical trailing headers after the signed
// terminal chunk of a STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER body.
func (c *ChunkVerifier) VerifyTrailer(signature string, trailerSHA256 []byte) error {
prefix := strings.TrimPrefix(c.prefix, streamingAlgorithm)
stringToSign := "AWS4-HMAC-SHA256-TRAILER" + prefix + c.previous + "\n" + hex.EncodeToString(trailerSHA256)
expected := hex.EncodeToString(hmacSHA256(c.signingKey, []byte(stringToSign)))
if !hmac.Equal([]byte(expected), []byte(signature)) {
return ErrChunkSignatureMismatch
}
return nil
}
33 changes: 33 additions & 0 deletions auth/chunk_verifier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,36 @@ func TestValidate_FailsWithoutOutcome(t *testing.T) {
t.Fatalf("Validate = (%v, %v), want (nil, error)", vr, err)
}
}

func TestChunkVerifier_AuthenticatesTrailer(t *testing.T) {
vr, key, timeAndScope, previous := validatedStreamingPut(t)
signingTime, scope, _ := strings.Cut(timeAndScope, "\x00")
verifier := vr.ChunkVerifier()
for _, chunk := range [][]byte{[]byte("hello world"), nil} {
signature := chainSignature(key, signingTime, scope, previous, chunk)
sum := sha256.Sum256(chunk)
if err := verifier.VerifyChunk(signature, sum[:]); err != nil {
t.Fatal(err)
}
previous = signature
}
sum := sha256.Sum256([]byte("x-amz-checksum-sha256:checksum\n"))
text := strings.Join([]string{"AWS4-HMAC-SHA256-TRAILER", signingTime, scope, previous, hex.EncodeToString(sum[:])}, "\n")
mac := hmac.New(sha256.New, key)
mac.Write([]byte(text))
signature := hex.EncodeToString(mac.Sum(nil))
if err := verifier.VerifyTrailer(signature, sum[:]); err != nil {
t.Fatal(err)
}
tampered := sum
tampered[0] ^= 1
if err := verifier.VerifyTrailer(signature, tampered[:]); !errors.Is(err, ErrChunkSignatureMismatch) {
t.Fatalf("changed trailer: %v", err)
}
if err := vr.ChunkVerifier().VerifyTrailer(signature, sum[:]); !errors.Is(err, ErrChunkSignatureMismatch) {
t.Fatalf("trailer without its chunk chain: %v", err)
}
if err := verifier.VerifyTrailer(strings.Repeat("0", 64), sum[:]); !errors.Is(err, ErrChunkSignatureMismatch) {
t.Fatalf("wrong trailer signature: %v", err)
}
}
27 changes: 27 additions & 0 deletions auth/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,33 @@ type ValidatedRequest struct {
signature string
}

// Resign signs a modified request as the validated caller, using the same
// credential scope, signing time and authentication form. The caller must own
// the request headers and URL. A signed streaming body must be decoded with a
// verifier seeded by the original request signature, not the new signature.
func (vr *ValidatedRequest) Resign(r *http.Request) {
r.Header.Set("Host", r.Host)
r.Header.Set("X-Amz-Date", vr.signingTime)
canonical, signedHeaders := (&RequestSigner{}).buildCanonicalRequest(r, r.Header.Get("X-Amz-Content-Sha256"))
presigned := r.Header.Get("Authorization") == ""
if presigned {
query := r.URL.Query()
query.Set("X-Amz-SignedHeaders", signedHeaders)
r.URL.RawQuery = query.Encode()
canonical = (&RequestValidator{}).buildCanonicalRequestPresigned(r, strings.Split(signedHeaders, ";"), unsignedPayload)
}
stringToSign := strings.Join([]string{algorithm, vr.signingTime, vr.scope, hashSHA256([]byte(canonical))}, "\n")
signature := hex.EncodeToString(hmacSHA256(vr.signingKey, []byte(stringToSign)))
if presigned {
query := r.URL.Query()
query.Set("X-Amz-Signature", signature)
r.URL.RawQuery = query.Encode()
return
}
r.Header.Set("Authorization", fmt.Sprintf("%s Credential=%s/%s, SignedHeaders=%s, Signature=%s",
algorithm, vr.AccessKey, vr.scope, signedHeaders, signature))
}

// ChunkVerifier returns a verifier for the request's signed chunk chain.
func (vr *ValidatedRequest) ChunkVerifier() *ChunkVerifier {
return &ChunkVerifier{
Expand Down
99 changes: 99 additions & 0 deletions auth/validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,17 @@ import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"testing"
"time"

"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
)

func TestRequestValidator_ValidateRequest(t *testing.T) {
Expand Down Expand Up @@ -173,3 +179,96 @@ func TestRequestValidator_ValidateRequest_MissingContentHash(t *testing.T) {
t.Errorf("ValidateRequest() error = %v, want %v", err, ErrMissingContentHash)
}
}

// A learned derived key must re-sign a changed request without substituting
// TAG's background identity. Compare with the SDK, not TAG's own validator.
func TestValidatedRequestResign(t *testing.T) {
const accessKey = "caller-access-key"
const secretKey = "caller-secret-key"
for _, derived := range []bool{false, true} {
t.Run(fmt.Sprintf("derived=%v", derived), func(t *testing.T) {
now := time.Now().UTC().Truncate(time.Second)
r := httptest.NewRequest(http.MethodPut, "https://objects.example/bucket/a%20key?x=two&x=one", nil)
r.Header.Set("If-Match", `"local-only-etag"`)
r.Header.Set("X-Amz-Content-Sha256", emptyBodyHash)
r.Header.Add("X-Amz-Meta-Colour", "blue")
r.Header.Add("X-Amz-Meta-Colour", "green")
creds := aws.Credentials{AccessKeyID: accessKey, SecretAccessKey: secretKey}
sdk := v4.NewSigner(func(o *v4.SignerOptions) { o.DisableURIPathEscaping = true })
if err := sdk.SignHTTP(t.Context(), creds, r, emptyBodyHash, "s3", "us-east-1", now); err != nil {
t.Fatal(err)
}
store := NewCredentialStore()
store.AddCredential(accessKey, secretKey)
validator := NewRequestValidator(store)
if derived {
keys := NewDerivedKeyStore(time.Hour)
date := now.Format("20060102")
keys.Store(accessKey, date, "us-east-1", NewRequestSigner("https://objects.example", "us-east-1").deriveSigningKey(secretKey, date))
validator = NewRequestValidator(keys)
}
// Match net/http's inbound request shape: Host is not URL.Host.
r.URL.Scheme, r.URL.Host = "", ""
vr, err := validator.Validate(r)
if err != nil {
t.Fatalf("validate caller: %v", err)
}
r.Header.Del("If-Match")
vr.Resign(r)
got := r.Header.Get("Authorization")
expected := r.Clone(t.Context())
expected.Header.Del("Host")
if err := sdk.SignHTTP(t.Context(), creds, expected, emptyBodyHash, "s3", "us-east-1", now); err != nil {
t.Fatal(err)
}
if got != expected.Header.Get("Authorization") {
t.Fatalf("re-signed caller request differs from SDK: got %q, want %q", got, expected.Header.Get("Authorization"))
}
})
}
}

func TestValidatedRequestResignPresigned(t *testing.T) {
now := time.Now().UTC().Truncate(time.Second)
credentials := aws.Credentials{AccessKeyID: "caller", SecretAccessKey: "secret", SessionToken: "session-token"}
r := httptest.NewRequest(http.MethodPut, "https://objects.example/bucket/a%20key?X-Amz-Expires=60", nil)
r.Header.Set("If-Match", `"local-only-etag"`)
r.Header.Set("X-Amz-Content-Sha256", unsignedPayload)
sdk := v4.NewSigner(func(o *v4.SignerOptions) { o.DisableURIPathEscaping = true; o.DisableHeaderHoisting = true })
uri, _, err := sdk.PresignHTTP(t.Context(), credentials, r, unsignedPayload, "s3", "us-east-1", now)
if err != nil {
t.Fatal(err)
}
r.URL, err = url.Parse(uri)
if err != nil {
t.Fatal(err)
}
store := NewCredentialStore()
store.AddCredential(credentials.AccessKeyID, credentials.SecretAccessKey)
vr, err := NewRequestValidator(store).Validate(r)
if err != nil {
t.Fatal(err)
}
r.URL.Scheme, r.URL.Host = "", ""
r.Header.Del("If-Match")
vr.Resign(r)
if r.Header.Get("Authorization") != "" {
t.Fatal("re-signing replaced query authentication with header authentication")
}
expected := r.Clone(t.Context())
expected.Header.Del("Host")
query := expected.URL.Query()
query.Del("X-Amz-Signature")
expected.URL.RawQuery = query.Encode()
uri, _, err = sdk.PresignHTTP(t.Context(), credentials, expected, unsignedPayload, "s3", "us-east-1", now)
if err != nil {
t.Fatal(err)
}
sdkURL, err := url.Parse(uri)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(r.URL.Query(), sdkURL.Query()) {
t.Fatalf("re-signed query differs from SDK: got %v, want %v", r.URL.Query(), sdkURL.Query())
}
}
31 changes: 26 additions & 5 deletions docs/tiered-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,26 @@ TAG stores a metadata marker locally. HEAD answers from the marker; GET
forwards for the body — the mode's only body traffic. DELETE forwards and
drops the marker.

**PUT preconditions follow the prior tier, not the replacement's size.** For a
validated plain-object PUT, TAG evaluates `If-Match` and `If-None-Match` against
the servable local prior (or confirmed absence), even when the replacement
belongs upstream. A failed condition does not forward or replace the prior.
After a local condition succeeds, TAG removes it from the forwarded request
and re-signs as the same caller. HMAC-signed streaming bodies are verified
while forwarding. Streams with signed trailers are re-framed, checking the
original chunk chain and trailer signature before the forwarded upload can
complete, and keeping the checksum trailers for upstream validation. Unsigned
trailer streams keep their original framing; signed streaming algorithms TAG
cannot verify are not converted on this path. With an upstream-tier prior,
upstream still evaluates the original conditions. A metadata or local-body
probe error is retryable, not absence.

The metadata snapshot used for the condition also guards publication of the
upstream marker. With CAS coordination, a competing metadata write can refuse
that publication. Legacy coordination retains its existing write-vs-write
check-then-store window. The upstream write and local metadata commit are not
one atomic transaction.

**Cross-tier overwrites clean up the displaced version.** A small write over an
upstream-tier object deletes the upstream copy asynchronously (best-effort —
a failure leaves an orphan for the upstream bucket's own expiry to collect).
Expand Down Expand Up @@ -85,8 +105,8 @@ counted in `tag_cache_populate_disk_shed_total`; see

## Authentication

The transparent-proxy flow, unchanged. Tiered semantics apply only to requests
whose SigV4 signature TAG validated locally; a request it cannot validate yet
Tiered mode uses the transparent-proxy authentication flow. Tiered semantics
apply only to requests whose SigV4 signature TAG validated locally; a request it cannot validate yet
(unknown key, anonymous) forwards to upstream exactly as in transparent mode,
and keys are learned from those responses. Until keys are learned, reads
behave like cache misses, and small writes land in the upstream tier (with a
Expand All @@ -97,9 +117,10 @@ on their first validated read.
**Forwarding flavor is decided by the endpoint.** Tiering is a caching
topology, not a forwarding flavor: a tiered deployment fronting a Tigris
domain (`*.tigris.dev`, `*.storage.dev`) forwards the transparent way (client
signature preserved, `X-Tigris-Proxy-*` identity headers, keys learned from
Tigris); one fronting any other endpoint — including `localhost`, which
transparent mode allows for local testing but which earns no trust claim
signature preserved unless a local PUT condition was consumed,
`X-Tigris-Proxy-*` identity headers, keys learned from Tigris); one fronting any
other endpoint — including `localhost`, which transparent mode allows for local
testing but which earns no trust claim
about the backend behind it — forwards the signing way (TAG validates the
caller against its credential store and re-signs). The startup log states
which flavor was selected.
Expand Down
23 changes: 23 additions & 0 deletions proxy/chunk_verify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"reflect"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -688,4 +689,26 @@ func TestHeadersForForwardedSigning(t *testing.T) {
if got := headersForForwardedSigning(client, false); got.Get("X-Amz-Decoded-Content-Length") != "10" {
t.Fatalf("non-chunked headers altered: %v", got)
}
for _, tc := range []struct {
name string
values []string
want string
}{
{"separate fields", []string{"aws-chunked", "gzip"}, "gzip"},
{"framing last", []string{"gzip", "aws-chunked"}, "gzip"},
{"multiple encodings", []string{"aws-chunked, gzip", "br"}, "gzip,br"},
{"empty first field", []string{"", "aws-chunked", "gzip"}, "gzip"},
{"framing only", []string{"aws-chunked", "aws-chunked"}, ""},
} {
t.Run(tc.name, func(t *testing.T) {
client := http.Header{"Content-Encoding": tc.values}
original := client.Clone()
if got := headersForForwardedSigning(client, true).Get("Content-Encoding"); got != tc.want {
t.Errorf("decoded content encoding = %q, want %q", got, tc.want)
}
if !reflect.DeepEqual(client, original) || !reflect.DeepEqual(headersForForwardedSigning(client, false), original) {
t.Error("client or non-chunked headers altered")
}
})
}
}
10 changes: 10 additions & 0 deletions proxy/chunked_reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ type awsChunkedReader struct {
// has claimed yet; -1 when the request declared no decoded length.
// Verifying readers only.
undeclared int64

// Optional authentication of trailers after the terminal chunk. It runs
// before done is set or the final payload byte is released.
verifyTerminal func(int64) error
}

// awsChunkedReaderBufSize is the decoder's internal bufio buffer. Named so
Expand Down Expand Up @@ -307,6 +311,12 @@ func (r *awsChunkedReader) readChunkHeader() error {
}

if size <= 0 {
if r.verifyTerminal != nil {
if err := r.verifyTerminal(size); err != nil {
r.err = err
return err
}
}
r.done = true
return nil
}
Expand Down
Loading
Loading