wip: option B writer core (not for review)
Writer user, session policy, state object, mint and revoke walks, grant and teardown hooks, AWS adapter, unit and policy-evaluation tests. Held on Paul's go for a fourth design round; not pushed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+1,695
−4
internal/console/claim_backend_recorders_test.go+7 −0internal/console/claim_backends.go+12 −0internal/console/claim_purge_backend.go+11 −0internal/console/claim_store_effects.go+12 −0internal/objstore/aws.go+9 −1internal/objstore/aws_writecred.go+199 −0internal/objstore/memprovisioner.go+84 −0internal/objstore/provisioner.go+13 −1internal/objstore/walk.go+26 −2internal/objstore/writecred.go+501 −0internal/objstore/writecred_policy_test.go+323 −0internal/objstore/writecred_test.go+498 −0
diff --git a/internal/console/claim_backend_recorders_test.go b/internal/console/claim_backend_recorders_test.go| index 5f5ac7627..3bf454ee3 100644 |
| --- a/internal/console/claim_backend_recorders_test.go |
| +++ b/internal/console/claim_backend_recorders_test.go |
| @@ -3,6 +3,7 @@ package console |
| import ( |
| "context" |
| "encoding/json" |
| + "time" |
| "github.com/carlosframework/platform/internal/dnsrec" |
| "github.com/carlosframework/platform/internal/hostops" |
| @@ -112,6 +113,12 @@ func (w *StoreProvisionerBoundary) DeleteUser(ctx context.Context, user string) |
| } |
| return w.raw.DeleteUser(ctx, user) |
| } |
| +func (w *StoreProvisionerBoundary) EnsureWriter(context.Context, string, string, string) error { |
| + return objstore.ErrWriteCredentialsUnsupported |
| +} |
| +func (w *StoreProvisionerBoundary) MintSession(context.Context, string, string, time.Duration) (objstore.Session, error) { |
| + return objstore.Session{}, objstore.ErrWriteCredentialsUnsupported |
| +} |
| type ScannerBoundary struct { |
| raw objstore.Scanner |
diff --git a/internal/console/claim_backends.go b/internal/console/claim_backends.go| index 9882e7462..dec0d7d1d 100644 |
| --- a/internal/console/claim_backends.go |
| +++ b/internal/console/claim_backends.go |
| @@ -8,6 +8,7 @@ import ( |
| "fmt" |
| "os" |
| "strings" |
| + "time" |
| "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/dnsrec" |
| @@ -810,3 +811,14 @@ func (w claimDNSWriter) DeleteRecord(ctx context.Context, r dnsrec.Record) error |
| } |
| return w.raw.DeleteRecord(ctx, r) |
| } |
| + |
| +// EnsureWriter and MintSession are write credentials |
| +// (objstore/writecred.go), which a host-claim console never issues: the |
| +// doors refuse there, and this backend refuses too rather than journal an |
| +// effect no claim covers. |
| +func (p claimStoreProvisioner) EnsureWriter(context.Context, string, string, string) error { |
| + return objstore.ErrWriteCredentialsUnsupported |
| +} |
| +func (p claimStoreProvisioner) MintSession(context.Context, string, string, time.Duration) (objstore.Session, error) { |
| + return objstore.Session{}, objstore.ErrWriteCredentialsUnsupported |
| +} |
diff --git a/internal/console/claim_purge_backend.go b/internal/console/claim_purge_backend.go| index 926e5b1e9..b4647dec6 100644 |
| --- a/internal/console/claim_purge_backend.go |
| +++ b/internal/console/claim_purge_backend.go |
| @@ -184,3 +184,14 @@ func (p claimPurgeDNS) EnsureRecord(ctx context.Context, record dnsrec.Record) e |
| } |
| return p.e.run(ctx, "dns:"+record.Key(), "ensure", map[string]string{"record": string(raw)}, func(ctx context.Context) error { return p.raw.EnsureRecord(ctx, record) }) |
| } |
| + |
| +// EnsureWriter and MintSession are write credentials |
| +// (objstore/writecred.go), which a host-claim console never issues: the |
| +// doors refuse there, and this backend refuses too rather than journal an |
| +// effect no claim covers. |
| +func (p claimPurgeStore) EnsureWriter(context.Context, string, string, string) error { |
| + return objstore.ErrWriteCredentialsUnsupported |
| +} |
| +func (p claimPurgeStore) MintSession(context.Context, string, string, time.Duration) (objstore.Session, error) { |
| + return objstore.Session{}, objstore.ErrWriteCredentialsUnsupported |
| +} |
diff --git a/internal/console/claim_store_effects.go b/internal/console/claim_store_effects.go| index 3e867afc8..ed7a269ee 100644 |
| --- a/internal/console/claim_store_effects.go |
| +++ b/internal/console/claim_store_effects.go |
| @@ -7,6 +7,7 @@ import ( |
| "encoding/hex" |
| "encoding/json" |
| "io" |
| + "time" |
| "github.com/carlosframework/platform/internal/hostops" |
| "github.com/carlosframework/platform/internal/objstore" |
| @@ -153,3 +154,14 @@ func claimStoreAdapters(ctx context.Context, store release.Store, p objstore.Pro |
| } |
| return claimEffectStore{data: store, effects: e}, prov |
| } |
| + |
| +// EnsureWriter and MintSession are write credentials |
| +// (objstore/writecred.go), which a host-claim console never issues: the |
| +// doors refuse there, and this backend refuses too rather than journal an |
| +// effect no claim covers. |
| +func (p claimEffectProvisioner) EnsureWriter(context.Context, string, string, string) error { |
| + return objstore.ErrWriteCredentialsUnsupported |
| +} |
| +func (p claimEffectProvisioner) MintSession(context.Context, string, string, time.Duration) (objstore.Session, error) { |
| + return objstore.Session{}, objstore.ErrWriteCredentialsUnsupported |
| +} |
diff --git a/internal/objstore/aws.go b/internal/objstore/aws.go| index c8e02c080..a78303ec9 100644 |
| --- a/internal/objstore/aws.go |
| +++ b/internal/objstore/aws.go |
| @@ -10,6 +10,7 @@ import ( |
| "encoding/json" |
| "errors" |
| "fmt" |
| + "time" |
| "github.com/aws/aws-sdk-go-v2/aws" |
| awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| @@ -60,6 +61,13 @@ type awsProvisioner struct { |
| // user this provisioner creates. See EnsureUser for why it is not |
| // optional in any deployment whose console role can reach IAM. |
| boundary string |
| + // endpoint is the S3-compatible endpoint the S3 client was built for, |
| + // "" for AWS S3. MintSession refuses when it is set. |
| + endpoint string |
| + // newSTS and sleepFn are test seams for MintSession |
| + // (aws_writecred.go); nil means the real STS client and a real wait. |
| + newSTS func(id, secret string) stsAPI |
| + sleepFn func(context.Context, time.Duration) error |
| } |
| var _ Provisioner = (*awsProvisioner)(nil) |
| @@ -104,7 +112,7 @@ func NewAWSProvisionerWith(ctx context.Context, region, endpoint, boundary strin |
| return nil, fmt.Errorf("objstore: load aws config: %w", err) |
| } |
| iamClient := iam.NewFromConfig(cfg) |
| - return &awsProvisioner{s3: s3Client, s3v: s3Client, iam: iamClient, region: region, boundary: boundary}, nil |
| + return &awsProvisioner{s3: s3Client, s3v: s3Client, iam: iamClient, region: region, boundary: boundary, endpoint: endpoint}, nil |
| } |
| // S3ClientFor builds a bare *s3.Client the same way NewAWSProvisioner builds |
diff --git a/internal/objstore/aws_writecred.go b/internal/objstore/aws_writecred.go| new file mode 100644 |
| index 000000000..e00fc1a41 |
| --- /dev/null |
| +++ b/internal/objstore/aws_writecred.go |
| @@ -0,0 +1,199 @@ |
| +// The AWS half of write credentials (writecred.go, spec |
| +// 2026-11-25-store-write-credential-design.md §2, §5): the store's writer |
| +// user, and GetFederationToken called as the writer. |
| +// |
| +// GetFederationToken takes an IAM user's long-term keys and nothing else, |
| +// and the writer never holds one. So each mint makes a single-use key for |
| +// the writer, calls STS with it, and deletes it. The |
| +// key's secret lives in this process for those seconds and goes nowhere |
| +// else: not into a log line, an error, the record or the answer. |
| +package objstore |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| + "github.com/aws/aws-sdk-go-v2/service/iam" |
| + iamtypes "github.com/aws/aws-sdk-go-v2/service/iam/types" |
| + "github.com/aws/aws-sdk-go-v2/service/sts" |
| + "github.com/aws/smithy-go" |
| + "github.com/carlosframework/platform/internal/rootaws" |
| +) |
| + |
| +// stsAPI is the one STS call a mint makes. |
| +type stsAPI interface { |
| + GetFederationToken(ctx context.Context, in *sts.GetFederationTokenInput, optFns ...func(*sts.Options)) (*sts.GetFederationTokenOutput, error) |
| +} |
| + |
| +// singleUseKeyDeleteTimeout bounds the delete of a mint's single-use key. |
| +const singleUseKeyDeleteTimeout = 15 * time.Second |
| + |
| +// federationBackoff is the wait before each retry of GetFederationToken |
| +// while a new key or a just-written policy propagates (spec §5): about 30 |
| +// seconds in all. |
| +var federationBackoff = []time.Duration{ |
| + 500 * time.Millisecond, time.Second, 2 * time.Second, 4 * time.Second, |
| + 4 * time.Second, 4 * time.Second, 4 * time.Second, 4 * time.Second, 4 * time.Second, 4 * time.Second, |
| +} |
| + |
| +// EnsureWriter creates the writer under the store boundary if absent and |
| +// writes its one inline policy, under the store policy's name so DeleteUser |
| +// removes it as it removes a store user's. It is EnsureUser with the |
| +// writer's document: the console role's iam:CreateUser and |
| +// iam:PutUserPolicy are conditioned on this same boundary and scoped to |
| +// this same path, so the writer needs no new grant. |
| +func (p *awsProvisioner) EnsureWriter(ctx context.Context, name, path, policy string) error { |
| + in := &iam.CreateUserInput{UserName: aws.String(name), Path: aws.String(path)} |
| + if p.boundary != "" { |
| + in.PermissionsBoundary = aws.String(p.boundary) |
| + } |
| + if _, err := p.iam.CreateUser(ctx, in); err != nil { |
| + var exists *iamtypes.EntityAlreadyExistsException |
| + if !errors.As(err, &exists) { |
| + return fmt.Errorf("objstore: create writer %q: %w", name, err) |
| + } |
| + } |
| + if _, err := p.iam.PutUserPolicy(ctx, &iam.PutUserPolicyInput{ |
| + UserName: aws.String(name), |
| + PolicyName: aws.String(policyName), |
| + PolicyDocument: aws.String(policy), |
| + }); err != nil { |
| + return fmt.Errorf("objstore: put policy for writer %q: %w", name, err) |
| + } |
| + return nil |
| +} |
| + |
| +// MintSession is GetFederationToken as user (the store's writer), through |
| +// a single-use key. |
| +// |
| +// A provisioner whose S3 is at a custom endpoint refuses: its IAM is AWS's, |
| +// and an AWS STS session means nothing to another store. |
| +func (p *awsProvisioner) MintSession(ctx context.Context, user, policy string, ttl time.Duration) (Session, error) { |
| + if p.endpoint != "" { |
| + return Session{}, ErrWriteCredentialsUnsupported |
| + } |
| + if err := ValidWriteTTL(ttl); err != nil { |
| + return Session{}, err |
| + } |
| + // The writer is never given a key and mints never overlap (the caller |
| + // holds the store's walk lock), so any key it has is one a crashed mint |
| + // left behind, whose secret died with that process. Reaping them all |
| + // keeps a free slot for this mint's key. |
| + if err := p.ReapKeys(ctx, user, nil); err != nil { |
| + return Session{}, err |
| + } |
| + made, err := p.iam.CreateAccessKey(ctx, &iam.CreateAccessKeyInput{UserName: aws.String(user)}) |
| + if err != nil { |
| + return Session{}, fmt.Errorf("objstore: create single-use key for %q: %w", user, err) |
| + } |
| + id, secret := aws.ToString(made.AccessKey.AccessKeyId), aws.ToString(made.AccessKey.SecretAccessKey) |
| + defer func() { |
| + // Detached from the request's cancellation: the key must die even |
| + // when the caller has gone away, or it holds one of the user's two |
| + // slots until a rotation reaps it. Bounded on its own instead. |
| + dctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), singleUseKeyDeleteTimeout) |
| + defer cancel() |
| + if err := p.DeleteKey(dctx, user, id); err != nil { |
| + log.Printf("objstore: single-use key %s of %s was not deleted (the next mint reaps it): %v", id, user, err) |
| + } |
| + }() |
| + client, err := p.stsClient(ctx, id, secret) |
| + if err != nil { |
| + return Session{}, fmt.Errorf("objstore: sts client: %w", err) |
| + } |
| + name, err := federatedName() |
| + if err != nil { |
| + return Session{}, err |
| + } |
| + in := &sts.GetFederationTokenInput{ |
| + Name: aws.String(name), |
| + Policy: aws.String(policy), |
| + DurationSeconds: aws.Int32(int32(ttl / time.Second)), |
| + } |
| + var out *sts.GetFederationTokenOutput |
| + for attempt := 0; ; attempt++ { |
| + out, err = client.GetFederationToken(ctx, in) |
| + if err == nil || !federationRetryable(err) || attempt >= len(federationBackoff) { |
| + break |
| + } |
| + if serr := p.sleep(ctx, federationBackoff[attempt]); serr != nil { |
| + return Session{}, serr |
| + } |
| + } |
| + if err != nil { |
| + return Session{}, fmt.Errorf("objstore: get federation token as %q: %w", user, err) |
| + } |
| + cr := out.Credentials |
| + if cr == nil || cr.AccessKeyId == nil || cr.SecretAccessKey == nil || cr.SessionToken == nil || cr.Expiration == nil { |
| + return Session{}, errors.New("objstore: get federation token: the answer holds no complete credentials") |
| + } |
| + return Session{ |
| + AccessKeyID: *cr.AccessKeyId, |
| + SecretAccessKey: *cr.SecretAccessKey, |
| + SessionToken: *cr.SessionToken, |
| + // AWS's clock: Expiration is the issue time plus the duration |
| + // asked for. |
| + Issued: cr.Expiration.Add(-ttl), |
| + Expires: *cr.Expiration, |
| + }, nil |
| +} |
| + |
| +// federationRetryable is an STS answer that a few seconds can change: a key |
| +// made a moment ago is not yet known everywhere (InvalidClientTokenId), and |
| +// a policy written a moment ago is not yet in force (AccessDenied). |
| +func federationRetryable(err error) bool { |
| + var apiErr smithy.APIError |
| + if !errors.As(err, &apiErr) { |
| + return false |
| + } |
| + switch apiErr.ErrorCode() { |
| + case "InvalidClientTokenId", "AccessDenied", "AccessDeniedException": |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +// federatedName is a fresh session name under FederatedNamePrefix: 29 |
| +// characters, inside STS's 32. |
| +func federatedName() (string, error) { |
| + var b [8]byte |
| + if _, err := rand.Read(b[:]); err != nil { |
| + return "", fmt.Errorf("objstore: session name: %w", err) |
| + } |
| + return FederatedNamePrefix + hex.EncodeToString(b[:]), nil |
| +} |
| + |
| +// stsClient is an STS client signing as the single-use key, through |
| +// rootaws's bounded transport, or the test's stub. |
| +func (p *awsProvisioner) stsClient(ctx context.Context, id, secret string) (stsAPI, error) { |
| + if p.newSTS != nil { |
| + return p.newSTS(id, secret), nil |
| + } |
| + cfg, err := rootaws.LoadStaticConfig(ctx, id, secret, awsconfig.WithRegion(p.region)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return sts.NewFromConfig(cfg), nil |
| +} |
| + |
| +// sleep waits d or until ctx ends; a test replaces it. |
| +func (p *awsProvisioner) sleep(ctx context.Context, d time.Duration) error { |
| + if p.sleepFn != nil { |
| + return p.sleepFn(ctx, d) |
| + } |
| + t := time.NewTimer(d) |
| + defer t.Stop() |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-t.C: |
| + return nil |
| + } |
| +} |
diff --git a/internal/objstore/memprovisioner.go b/internal/objstore/memprovisioner.go| index 1b68971ca..63340021f 100644 |
| --- a/internal/objstore/memprovisioner.go |
| +++ b/internal/objstore/memprovisioner.go |
| @@ -3,7 +3,9 @@ package objstore |
| import ( |
| "context" |
| "fmt" |
| + "strings" |
| "sync" |
| + "time" |
| ) |
| // MemUser is the in-memory fake's view of an IAM principal: its ARN and its |
| @@ -19,6 +21,15 @@ type MemUser struct { |
| Policy string |
| } |
| +// MemSession is one session MintSession handed out, with the scope it was |
| +// narrowed by. |
| +type MemSession struct { |
| + User string |
| + Policy string |
| + TTL time.Duration |
| + Issued time.Time |
| +} |
| + |
| // MemProvisioner is an in-memory Provisioner for walk tests: no AWS, no |
| // network, deterministic key ids. It stays in this package (internal) — |
| // nothing outside objstore needs to reach into its state. |
| @@ -47,6 +58,21 @@ type MemProvisioner struct { |
| Versioning map[string]*MemBucketVersioning |
| Restores []string |
| nextVersion int |
| + |
| + // Sessions is every session MintSession handed out, in order. |
| + // AWSClock, when set, is the backend's clock a session's Issued is |
| + // read from, so a test can skew it against the console's. |
| + Sessions []MemSession |
| + AWSClock func() time.Time |
| + // SingleUseKeys counts the access keys MintSession created and deleted |
| + // for its STS call, as the AWS adapter does: they never appear in Keys |
| + // once MintSession returns. WriterWrites counts EnsureWriter calls. |
| + SingleUseKeys int |
| + WriterWrites int |
| + // AfterEnsureWriter, when set, runs after each EnsureWriter write, with |
| + // the lock released: the seam for a test that races another writer of |
| + // the store's state between a write and its validation. |
| + AfterEnsureWriter func(name string) |
| } |
| // NewMemProvisioner returns an empty fake that answers region for every |
| @@ -212,3 +238,61 @@ func (p *MemProvisioner) DeleteUser(ctx context.Context, user string) error { |
| delete(p.Users, user) |
| return nil |
| } |
| + |
| +// EnsureWriter creates the writer if absent and records its policy. |
| +func (p *MemProvisioner) EnsureWriter(ctx context.Context, name, path, policy string) error { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + if err := p.takeFailure("EnsureWriter"); err != nil { |
| + return err |
| + } |
| + u, ok := p.Users[name] |
| + if !ok { |
| + u = MemUser{ARN: "arn:mem:iam::user" + path + name, Keys: map[string]string{}} |
| + } |
| + u.Policy = policy |
| + p.Users[name] = u |
| + p.WriterWrites++ |
| + if hook := p.AfterEnsureWriter; hook != nil { |
| + p.mu.Unlock() |
| + defer p.mu.Lock() |
| + hook(name) |
| + } |
| + return nil |
| +} |
| + |
| +// MintSession is the AWS adapter's shape without AWS: it refuses a user |
| +// whose policy does not let it call GetFederationToken (IAM would answer |
| +// AccessDenied), reaps any key the user holds (a crashed mint's), and |
| +// otherwise records the session and its scope. |
| +func (p *MemProvisioner) MintSession(ctx context.Context, user, policy string, ttl time.Duration) (Session, error) { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + if err := p.takeFailure("MintSession"); err != nil { |
| + return Session{}, err |
| + } |
| + u, ok := p.Users[user] |
| + if !ok { |
| + return Session{}, fmt.Errorf("objstore: mem: no such user %q", user) |
| + } |
| + if !strings.Contains(u.Policy, `"sts:GetFederationToken"`) { |
| + return Session{}, fmt.Errorf("objstore: mem: AccessDenied: %s may not call GetFederationToken", user) |
| + } |
| + for id := range u.Keys { |
| + delete(u.Keys, id) |
| + } |
| + p.SingleUseKeys++ |
| + now := time.Now() |
| + if p.AWSClock != nil { |
| + now = p.AWSClock() |
| + } |
| + p.Sessions = append(p.Sessions, MemSession{User: user, Policy: policy, TTL: ttl, Issued: now}) |
| + n := len(p.Sessions) |
| + return Session{ |
| + AccessKeyID: fmt.Sprintf("MEMSESSION%d", n), |
| + SecretAccessKey: fmt.Sprintf("MEMSESSIONSECRET%d", n), |
| + SessionToken: fmt.Sprintf("MEMSESSIONTOKEN%d", n), |
| + Issued: now, |
| + Expires: now.Add(ttl), |
| + }, nil |
| +} |
diff --git a/internal/objstore/provisioner.go b/internal/objstore/provisioner.go| index d5b0b8da5..0784e28f0 100644 |
| --- a/internal/objstore/provisioner.go |
| +++ b/internal/objstore/provisioner.go |
| @@ -1,6 +1,9 @@ |
| package objstore |
| -import "context" |
| +import ( |
| + "context" |
| + "time" |
| +) |
| // Provisioner is the backend seam (§3): everything the console needs a |
| // backend to do, and nothing an app ever calls. Every method is idempotent — |
| @@ -32,4 +35,13 @@ type Provisioner interface { |
| DeleteBucket(ctx context.Context, name string) error |
| // DeleteUser removes the user's keys and inline policy first. |
| DeleteUser(ctx context.Context, user string) error |
| + // EnsureWriter creates the store's writer user (writecred.go) under the |
| + // store boundary if absent, and writes its inline policy: an overwrite, |
| + // like EnsureUser's. |
| + EnsureWriter(ctx context.Context, name, path, policy string) error |
| + // MintSession mints a temporary credential for user, narrowed by the |
| + // IAM session policy policy, lasting ttl. It never answers a lasting |
| + // credential: a backend that cannot narrow a session answers |
| + // ErrWriteCredentialsUnsupported. Session.Issued is the backend's clock. |
| + MintSession(ctx context.Context, user, policy string, ttl time.Duration) (Session, error) |
| } |
diff --git a/internal/objstore/walk.go b/internal/objstore/walk.go| index 33e0a9974..03ae43593 100644 |
| --- a/internal/objstore/walk.go |
| +++ b/internal/objstore/walk.go |
| @@ -332,6 +332,14 @@ func claimRawGrantIn(ctx context.Context, s release.Store, p Provisioner, d Depl |
| if err != nil { |
| return nil, fmt.Errorf("objstore: ensure user %s: %w", user, err) |
| } |
| + // 2a. the store's writer (writecred.go), if it has one: its policy |
| + // carries the storage-grace Deny too, and this walk is how a change to |
| + // writes_denied reaches it. A store with no bucket yet has no writer. |
| + if rec.Provisioned != nil { |
| + if err := claimRawConvergeWriterIn(ctx, s, p, acct, app, env, bucket); err != nil { |
| + return nil, err |
| + } |
| + } |
| // 2b. versioning, for a store that already has its bucket. Before the |
| // short-circuit for the policy's reason: versioning is turned on for a |
| // store that already exists, and a healthy re-walk must still converge |
| @@ -803,6 +811,21 @@ func claimRawTeardownIn(ctx context.Context, s release.Store, p Provisioner, sc |
| } else if err := p.DeleteUser(ctx, user); err != nil { |
| return fmt.Errorf("objstore: delete user %s: %w", user, err) |
| } |
| + // The store's writer (writecred.go), if it has one: the user (with its |
| + // policy and any key a crashed mint left), then the state object that |
| + // names it. Both are idempotent, so a re-run after a failure between |
| + // them converges, and the record, read first, still goes last. |
| + if wc, _, err := GetWriteCredentialsIn(ctx, s, acct, app, env); err != nil { |
| + return fmt.Errorf("objstore: read write credentials for %s/%s: %w", acct, app, err) |
| + } else if wc != nil { |
| + writer := WriterName(UserNameIn(acct, app, env)) |
| + if err := p.DeleteUser(ctx, writer); err != nil { |
| + return fmt.Errorf("objstore: delete writer %s: %w", writer, err) |
| + } |
| + if err := s.Delete(ctx, WriteCredentialsKey(acct, app, env)); err != nil { |
| + return fmt.Errorf("objstore: delete write credentials state for %s/%s: %w", acct, app, err) |
| + } |
| + } |
| // The delivered set goes even though the credentials behind it are already |
| // dead: leaving them would hand the app's next render a bucket name and a |
| // key that authenticate against nothing, which is harder to debug than an |
| @@ -830,8 +853,9 @@ func claimRawTeardownIn(ctx context.Context, s release.Store, p Provisioner, sc |
| if err := unsetDelivered(ctx, s, acct, app, env, unsets); err != nil { |
| return err |
| } |
| - // The scan sidecar, before the record. It is the only other object under |
| - // this app's prefix that this package writes, and an orphan left behind |
| + // The scan sidecar, before the record. With the write credentials state |
| + // above, it is the only other object under this app's prefix that this |
| + // package writes, and an orphan left behind |
| // makes the app NAME unusable: the claim gate refuses a name whose prefix |
| // still holds any key, and the box-side auto-purge never reaches it |
| // because the tombstone goes last. Delete is idempotent on an absent key, |
diff --git a/internal/objstore/writecred.go b/internal/objstore/writecred.go| new file mode 100644 |
| index 000000000..709d7eb55 |
| --- /dev/null |
| +++ b/internal/objstore/writecred.go |
| @@ -0,0 +1,501 @@ |
| +// Write credentials (spec 2026-11-25-store-write-credential-design.md): a |
| +// temporary credential that can only upload objects under one key prefix of |
| +// an app's own store, for an app to hand to a third party such as a LiveKit |
| +// recorder. This file is the provider-neutral half: what a write credential |
| +// may do (the session policy), which prefixes and lifetimes are allowed, |
| +// the store's writer user and its policy, the state object behind it, and |
| +// the walks. It imports no cloud SDK; aws_writecred.go is the AWS adapter |
| +// behind Provisioner.EnsureWriter and Provisioner.MintSession. |
| +// |
| +// THE CEILING IS THE STORE'S WRITER. A write credential is a federation |
| +// session of the writer, a second IAM user per store that may only write |
| +// its store's one bucket and never holds a lasting key (spec §2, option B). |
| +// Whatever the session policy says, the session can never do more than |
| +// that. The app's own key is the store user's, which cannot call |
| +// GetFederationToken at all, so no session outlives a rotation of it. |
| +package objstore |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +const ( |
| + // WriteCredentialMinTTL is STS's floor for a federation session. |
| + WriteCredentialMinTTL = 15 * time.Minute |
| + // WriteCredentialMaxTTL covers LiveKit Cloud's longest egress (12 hours) |
| + // plus its upload at the end, below STS's own 36-hour cap so that a |
| + // leaked credential lives no longer than a recording needs (spec §4). |
| + WriteCredentialMaxTTL = 24 * time.Hour |
| + // FederatedNamePrefix starts the name of every federation session this |
| + // platform mints. The boundary allows GetFederationToken only for names |
| + // under it. |
| + FederatedNamePrefix = "carlos-write-" |
| + // writerNamePrefix replaces the store user's "carlos-store-" in its |
| + // writer's name (WriterName). |
| + writerNamePrefix = "carlos-w-" |
| + // writePrefixMax bounds the prefix, and with it the session policy, |
| + // which STS refuses past 2,048 characters. |
| + writePrefixMax = 200 |
| + // clockBound is ε in spec §2.3: how far the console's clock is assumed |
| + // to be from AWS's. A revocation reaches ε past the console's clock, and |
| + // a mint waits ε past the revocation, so either sign of skew up to ε is |
| + // covered. MintSession's AWS-side issue time is the exact check on top. |
| + clockBound = time.Minute |
| + // writeCredentialsSchema is the state object's schema. |
| + writeCredentialsSchema = 1 |
| +) |
| + |
| +var ( |
| + // ErrBadWritePrefix is a prefix the write credential cannot be scoped |
| + // to (ValidWritePrefix says which rule). |
| + ErrBadWritePrefix = errors.New("objstore: write credential prefix") |
| + // ErrBadWriteTTL is a lifetime outside WriteCredentialMinTTL to |
| + // WriteCredentialMaxTTL, or not a whole number of seconds. |
| + ErrBadWriteTTL = errors.New("objstore: write credential lifetime") |
| + // ErrWriteCredentialsUnsupported is a store, or a backend, that cannot |
| + // mint a narrowed temporary credential. Nothing falls back to the |
| + // store's full credential. |
| + ErrWriteCredentialsUnsupported = errors.New("objstore: this store cannot issue write credentials") |
| + // errWriterUnsettled is a writer policy whose inputs kept changing |
| + // under three writes in a row (claimRawConvergeWriterIn). |
| + errWriterUnsettled = errors.New("objstore: the writer's policy inputs kept changing; retry") |
| + // ErrNoWriteCredentials is a revocation for a store that never issued a |
| + // write credential: there is nothing to revoke. |
| + ErrNoWriteCredentials = errors.New("objstore: this store has never issued a write credential") |
| + // ErrWriteCredentialsMismatch is a state object whose body disagrees |
| + // with the key it was read from. |
| + ErrWriteCredentialsMismatch = errors.New("objstore: write credentials state names another store") |
| +) |
| + |
| +// RevocationSettlingError is a mint refused while a revocation settles: a |
| +// session minted now could be issued, by AWS's clock, before the revocation |
| +// instant, and would be dead on arrival. |
| +type RevocationSettlingError struct{ Until time.Time } |
| + |
| +func (e *RevocationSettlingError) Error() string { |
| + return "objstore: write credentials were just revoked; mint again after " + e.Until.UTC().Format(time.RFC3339) |
| +} |
| + |
| +// Session is a temporary credential a backend minted (Provisioner.MintSession). |
| +// Issued is the backend's own clock, not the console's: it is what a |
| +// revocation's Deny compares. |
| +type Session struct { |
| + AccessKeyID string |
| + SecretAccessKey string |
| + SessionToken string |
| + Issued time.Time |
| + Expires time.Time |
| +} |
| + |
| +// WriteCredential is a minted write credential and the coordinates it |
| +// writes to. |
| +type WriteCredential struct { |
| + Session |
| + Bucket string |
| + Region string |
| + Prefix string |
| +} |
| + |
| +// WriteCredentials is the state object, apps/<acct>/<app>/write-credentials.json |
| +// (an environment store: write-credentials/<env>.json). Its presence says |
| +// the store has a writer user. RevokedBefore, once set, denies the writer's |
| +// every session issued before it: every write credential minted until then |
| +// (spec §2.4). |
| +// |
| +// It is a separate object from store.json on purpose: an older console |
| +// rewrites store.json through a struct that would drop it, and a revocation |
| +// must outlive a console rollback. |
| +type WriteCredentials struct { |
| + Schema int `json:"schema"` |
| + Account string `json:"account"` |
| + App string `json:"app"` |
| + Environment string `json:"environment,omitempty"` |
| + At time.Time `json:"at"` |
| + By string `json:"by"` |
| + RevokedBefore *time.Time `json:"revoked_before,omitempty"` |
| +} |
| + |
| +// WriteCredentialsKey is the state object's key for one store of an app. |
| +// Not under StoresPrefix: StoreEnvironments reads every key there as an |
| +// environment store. |
| +func WriteCredentialsKey(acct, app, env string) string { |
| + if env == "" { |
| + return release.AppPrefix(acct, app) + "write-credentials.json" |
| + } |
| + return release.AppPrefix(acct, app) + "write-credentials/" + env + ".json" |
| +} |
| + |
| +// GetWriteCredentialsIn reads the state object. Absent is (nil, "", nil). |
| +func GetWriteCredentialsIn(ctx context.Context, s release.Store, acct, app, env string) (*WriteCredentials, string, error) { |
| + if !release.ValidAccount(acct) || !release.ValidApp(app) { |
| + return nil, "", fmt.Errorf("objstore: invalid store %s/%s", acct, app) |
| + } |
| + if env != "" && !appconfig.ValidEnvironmentName(env) { |
| + return nil, "", fmt.Errorf("objstore: invalid environment %q", env) |
| + } |
| + key := WriteCredentialsKey(acct, app, env) |
| + raw, etag, err := s.Get(ctx, key) |
| + if err != nil { |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil, "", nil |
| + } |
| + return nil, "", err |
| + } |
| + var wc WriteCredentials |
| + if err := json.Unmarshal(raw, &wc); err != nil { |
| + return nil, "", fmt.Errorf("objstore: %s: %w", key, err) |
| + } |
| + if wc.Account != acct || wc.App != app || wc.Environment != env { |
| + return nil, "", fmt.Errorf("%w: %s", ErrWriteCredentialsMismatch, key) |
| + } |
| + return &wc, etag, nil |
| +} |
| + |
| +// claimRawPutWriteCredentialsIn writes the state object at etag ("" is |
| +// create-only), stamping its identity from the key. |
| +func claimRawPutWriteCredentialsIn(ctx context.Context, s release.Store, acct, app, env string, wc *WriteCredentials, etag string) (string, error) { |
| + wc.Schema = writeCredentialsSchema |
| + wc.Account, wc.App, wc.Environment = acct, app, env |
| + body, err := json.MarshalIndent(wc, "", " ") |
| + if err != nil { |
| + return "", err |
| + } |
| + return s.Put(ctx, WriteCredentialsKey(acct, app, env), append(body, '\n'), etag) |
| +} |
| + |
| +// ValidWritePrefix reports whether prefix is one a write credential may be |
| +// scoped to, wrapping ErrBadWritePrefix with the rule it breaks. The prefix |
| +// goes into an IAM Resource ARN, so the alphabet keeps out IAM's wildcards |
| +// (* and ?) and policy variables (${...}); the trailing slash stops |
| +// "recordings" from also matching "recordings-private/". |
| +func ValidWritePrefix(prefix string) error { |
| + switch { |
| + case prefix == "" || prefix == "/": |
| + return fmt.Errorf("%w: name a folder, such as recordings/; a write credential never covers the whole store", ErrBadWritePrefix) |
| + case len(prefix) > writePrefixMax: |
| + return fmt.Errorf("%w: at most %d characters", ErrBadWritePrefix, writePrefixMax) |
| + case !strings.HasSuffix(prefix, "/"): |
| + return fmt.Errorf("%w: end it with /, such as recordings/", ErrBadWritePrefix) |
| + case strings.HasPrefix(prefix, derivedPrefix): |
| + return fmt.Errorf("%w: %s is where media conversion writes its outputs", ErrBadWritePrefix, derivedPrefix) |
| + } |
| + for _, seg := range strings.Split(strings.TrimSuffix(prefix, "/"), "/") { |
| + if seg == "" || seg == "." || seg == ".." { |
| + return fmt.Errorf("%w: no empty, . or .. folder names", ErrBadWritePrefix) |
| + } |
| + for i := 0; i < len(seg); i++ { |
| + c := seg[i] |
| + if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-') { |
| + return fmt.Errorf("%w: letters, digits, dots, underscores, hyphens and / only", ErrBadWritePrefix) |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// derivedPrefix is where media conversion writes a store's outputs |
| +// (internal/media's output keys). A third party must not be able to plant |
| +// files there that look platform-made. |
| +const derivedPrefix = "derived/" |
| + |
| +// ValidWriteTTL reports whether d is a lifetime a write credential may have. |
| +func ValidWriteTTL(d time.Duration) error { |
| + if d < WriteCredentialMinTTL || d > WriteCredentialMaxTTL { |
| + return fmt.Errorf("%w: from %v to %v", ErrBadWriteTTL, WriteCredentialMinTTL, WriteCredentialMaxTTL) |
| + } |
| + if d%time.Second != 0 { |
| + return fmt.Errorf("%w: a whole number of seconds", ErrBadWriteTTL) |
| + } |
| + return nil |
| +} |
| + |
| +// sessionStatement is one statement of the two policies this file writes. |
| +// Unlike policyStatement it can say NotAction and NotResource, which the |
| +// write scope's Denies need. |
| +type sessionStatement struct { |
| + Effect string `json:"Effect"` |
| + Action []string `json:"Action,omitempty"` |
| + NotAction []string `json:"NotAction,omitempty"` |
| + Resource string `json:"Resource,omitempty"` |
| + NotResource string `json:"NotResource,omitempty"` |
| + Condition map[string]map[string]any `json:"Condition,omitempty"` |
| +} |
| + |
| +type sessionDocument struct { |
| + Version string `json:"Version"` |
| + Statement []sessionStatement `json:"Statement"` |
| +} |
| + |
| +func marshalSessionDocument(st ...sessionStatement) string { |
| + b, err := json.Marshal(sessionDocument{Version: "2012-10-17", Statement: st}) |
| + if err != nil { |
| + // Static strings and string slices: Marshal cannot fail. |
| + panic(fmt.Sprintf("objstore: marshal policy: %v", err)) |
| + } |
| + return string(b) |
| +} |
| + |
| +// writeActions are everything a write credential may do. PutObject also |
| +// authorises CreateMultipartUpload, UploadPart and CompleteMultipartUpload; |
| +// the other two let an uploader list and abandon its own parts. |
| +var writeActions = []string{"s3:PutObject", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"} |
| + |
| +// writeSessionPolicy is the scope of a write credential: writeActions under |
| +// prefix in bucket, and nothing else (spec §3). |
| +// |
| +// The two Denies after the Allow make the scope explicit rather than an |
| +// absence: a resource policy naming the session could otherwise grant |
| +// beyond it, and an explicit Deny wins over any Allow. The last Deny refuses |
| +// any upload that carries tags at all. The store user's own policy already |
| +// denies the platform's tag keys, and AWS asks for s3:PutObjectTagging, |
| +// which nothing here allows, for any x-amz-tagging; this states the same |
| +// property where the credential is defined, for a policy engine that reads |
| +// the header differently (AGENTS.md: absence is not the property). |
| +func writeSessionPolicy(bucket, prefix string) string { |
| + res := "arn:aws:s3:::" + bucket + "/" + prefix + "*" |
| + return marshalSessionDocument( |
| + sessionStatement{Effect: "Allow", Action: writeActions, Resource: res}, |
| + sessionStatement{Effect: "Deny", NotAction: writeActions, Resource: "*"}, |
| + sessionStatement{Effect: "Deny", Action: writeActions, NotResource: res}, |
| + sessionStatement{Effect: "Deny", Action: []string{"s3:PutObject"}, Resource: res, Condition: map[string]map[string]any{ |
| + "Null": {"s3:RequestObjectTagKeys": "false"}, |
| + }}, |
| + ) |
| +} |
| + |
| +// WriterName is the writer user of the store whose user is storeUser: |
| +// carlos-w-<acct>-<app>[-<env>]. Shorter than the store user's name, so it |
| +// always fits IAM's limit, and unique exactly when store user names are. |
| +func WriterName(storeUser string) string { |
| + return writerNamePrefix + strings.TrimPrefix(storeUser, "carlos-store-") |
| +} |
| + |
| +// writerPolicyJSON is the writer's one inline policy (spec §2.2): the write |
| +// actions on the store's bucket, leave to call GetFederationToken, the |
| +// store policy's Denys that bear on a write (the same Go values), the |
| +// storage-grace Deny while the record asks for it, and once revoked, a Deny |
| +// on everything to any session issued before RevokedBefore. |
| +// aws:TokenIssueTime is present only for temporary credentials. The STS |
| +// Resource is "*" here; the boundary pins it to session names under |
| +// FederatedNamePrefix in this account. |
| +func writerPolicyJSON(bucketARN string, denyWrites bool, wc *WriteCredentials) string { |
| + objects := bucketARN + "/*" |
| + doc := policyDocument{Version: "2012-10-17", Statement: []policyStatement{ |
| + {Effect: "Allow", Action: writeActions, Resource: objects}, |
| + {Effect: "Allow", Action: []string{"sts:GetFederationToken"}, Resource: "*"}, |
| + {Effect: "Deny", Action: []string{ |
| + "s3:PutObjectTagging", "s3:DeleteObjectTagging", |
| + "s3:PutObjectVersionTagging", "s3:DeleteObjectVersionTagging", |
| + }, Resource: objects}, |
| + {Effect: "Deny", Action: []string{"s3:PutObject"}, Resource: objects, Condition: map[string]map[string]any{ |
| + "ForAnyValue:StringEquals": {"s3:RequestObjectTagKeys": []string{TagVerdict, TagVersion, TagAt}}, |
| + }}, |
| + {Effect: "Deny", Action: historyObjectDenies, Resource: objects}, |
| + }} |
| + if denyWrites { |
| + doc.Statement = append(doc.Statement, policyStatement{Effect: "Deny", Action: []string{"s3:PutObject"}, Resource: objects}) |
| + } |
| + if wc != nil && wc.RevokedBefore != nil { |
| + doc.Statement = append(doc.Statement, policyStatement{Effect: "Deny", Action: []string{"*"}, Resource: "*", Condition: map[string]map[string]any{ |
| + "DateLessThan": {"aws:TokenIssueTime": wc.RevokedBefore.UTC().Format(time.RFC3339)}, |
| + }}) |
| + } |
| + b, err := json.Marshal(doc) |
| + if err != nil { |
| + panic(fmt.Sprintf("objstore: marshal writer policy: %v", err)) |
| + } |
| + return string(b) |
| +} |
| + |
| +// writerPolicyNow is the writer's policy as the bucket's current record and |
| +// state object ask for it, or "" when the store has no writer. |
| +func writerPolicyNow(ctx context.Context, s release.Store, acct, app, env, bucket string) (string, error) { |
| + wc, _, err := GetWriteCredentialsIn(ctx, s, acct, app, env) |
| + if err != nil || wc == nil { |
| + return "", err |
| + } |
| + rec, _, err := GetIn(ctx, s, acct, app, env) |
| + if err != nil { |
| + return "", err |
| + } |
| + if rec == nil || rec.Provisioned == nil || rec.Provisioned.Bucket != bucket { |
| + // The store went away or moved under the walk: no writer policy |
| + // for this bucket is current any more. |
| + return "", ErrNotProvisioned |
| + } |
| + return writerPolicyJSON("arn:aws:s3:::"+bucket, rec.WritesDenied != nil, wc), nil |
| +} |
| + |
| +// claimRawConvergeWriterIn makes the writer's policy match the store's |
| +// record and state object, for a store that has a writer (nothing to do |
| +// otherwise). The walks that write it do not share one console lock, so it |
| +// is write-then-validate (spec §2.3): write the policy computed from what |
| +// was read, read again, and write again if the answer changed. A |
| +// revocation writes the state object before the policy, so a write |
| +// computed from older inputs is always followed by one from newer ones. |
| +func claimRawConvergeWriterIn(ctx context.Context, s release.Store, p Provisioner, acct, app, env, bucket string) error { |
| + writer := WriterName(UserNameIn(acct, app, env)) |
| + want, err := writerPolicyNow(ctx, s, acct, app, env, bucket) |
| + if err != nil || want == "" { |
| + return err |
| + } |
| + for attempt := 0; attempt < 3; attempt++ { |
| + if err := p.EnsureWriter(ctx, writer, UserPath, want); err != nil { |
| + return fmt.Errorf("objstore: ensure writer %s: %w", writer, err) |
| + } |
| + now, err := writerPolicyNow(ctx, s, acct, app, env, bucket) |
| + if err != nil { |
| + return err |
| + } |
| + if now == want { |
| + return nil |
| + } |
| + want = now |
| + } |
| + return errWriterUnsettled |
| +} |
| + |
| +// writeStore is the provisioned store a write-credential walk acts on: its |
| +// record and the coordinates the record names, checked the way |
| +// claimRawConvergePolicyIn checks them. |
| +func writeStore(ctx context.Context, s release.Store, acct, app, env string) (*Record, string, error) { |
| + rec, _, err := GetIn(ctx, s, acct, app, env) |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + if rec == nil || rec.Grant == nil || rec.Provisioned == nil { |
| + return nil, "", ErrNotProvisioned |
| + } |
| + bucket := rec.Grant.Bucket |
| + if bucket == "" || bucket != rec.Provisioned.Bucket || !ValidBucketName(bucket) { |
| + return nil, "", fmt.Errorf("objstore: store %s/%s names bucket %q in its grant and %q as provisioned; run the grant to repair it", |
| + acct, app, rec.Grant.Bucket, rec.Provisioned.Bucket) |
| + } |
| + user := UserNameIn(acct, app, env) |
| + if rec.Provisioned.IAMUser != user || !ValidUserName(user) { |
| + return nil, "", fmt.Errorf("objstore: store %s/%s names IAM user %q, not %q; run the grant to repair it", |
| + acct, app, rec.Provisioned.IAMUser, user) |
| + } |
| + return rec, user, nil |
| +} |
| + |
| +// claimRawMintWriteCredentialIn mints a write credential for one store |
| +// (spec §5). It refuses, before anything is written, a bad prefix or |
| +// lifetime, a store that is not provisioned, a store at an S3-compatible |
| +// endpoint and a revocation still settling. Then it writes the state object |
| +// if this is the store's first, converges the writer (created on the first |
| +// mint), and mints as the writer. A rotation of the app's key is no reason |
| +// to refuse: the writer is another user with its own key slots. |
| +func claimRawMintWriteCredentialIn(ctx context.Context, s release.Store, p Provisioner, |
| + acct, app, env, by, prefix string, ttl time.Duration, now time.Time) (*WriteCredential, error) { |
| + if err := ValidWritePrefix(prefix); err != nil { |
| + return nil, err |
| + } |
| + if err := ValidWriteTTL(ttl); err != nil { |
| + return nil, err |
| + } |
| + rec, user, err := writeStore(ctx, s, acct, app, env) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if rec.Provisioned.Endpoint != "" { |
| + return nil, ErrWriteCredentialsUnsupported |
| + } |
| + wc, _, err := GetWriteCredentialsIn(ctx, s, acct, app, env) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if wc != nil && wc.RevokedBefore != nil { |
| + if until := wc.RevokedBefore.Add(clockBound); now.Before(until) { |
| + return nil, &RevocationSettlingError{Until: until} |
| + } |
| + } |
| + if wc == nil { |
| + wc = &WriteCredentials{At: now.UTC(), By: by} |
| + if _, err := claimRawPutWriteCredentialsIn(ctx, s, acct, app, env, wc, ""); err != nil { |
| + return nil, fmt.Errorf("objstore: record write credentials for %s/%s: %w", acct, app, err) |
| + } |
| + } |
| + bucket := rec.Provisioned.Bucket |
| + if err := claimRawConvergeWriterIn(ctx, s, p, acct, app, env, bucket); err != nil { |
| + return nil, err |
| + } |
| + sess, err := p.MintSession(ctx, WriterName(user), writeSessionPolicy(bucket, prefix), ttl) |
| + if err != nil { |
| + return nil, err |
| + } |
| + // The exact check (spec §2.4): by AWS's own clock, was this session |
| + // issued after the revocation? The Deny compares to the second, so a |
| + // session less than a second clear of it is treated as caught. |
| + if rb := wc.RevokedBefore; rb != nil && sess.Issued.Before(rb.Add(time.Second)) { |
| + return nil, &RevocationSettlingError{Until: now.Add(rb.Add(time.Second).Sub(sess.Issued)).Add(clockBound)} |
| + } |
| + return &WriteCredential{Session: sess, Bucket: bucket, Region: rec.Provisioned.Region, Prefix: prefix}, nil |
| +} |
| + |
| +// revocationInstant is when a revocation made at now reaches: ε past the |
| +// console's clock, rounded up to the whole second the policy carries, and |
| +// never earlier than one already in force. |
| +func revocationInstant(wc *WriteCredentials, now time.Time) time.Time { |
| + t := now.UTC().Add(clockBound).Truncate(time.Second).Add(time.Second) |
| + if wc.RevokedBefore != nil && wc.RevokedBefore.After(t) { |
| + t = wc.RevokedBefore.UTC() |
| + } |
| + return t |
| +} |
| + |
| +// claimRawRevokeWriteCredentialsIn is `carlos store credential --revoke`: |
| +// every write credential of the store minted until now stops working once |
| +// the writer's policy has propagated. The state object first, then the |
| +// policy, which is the order write-then-validate relies on. |
| +func claimRawRevokeWriteCredentialsIn(ctx context.Context, s release.Store, p Provisioner, acct, app, env string, now time.Time) (time.Time, error) { |
| + rec, _, err := writeStore(ctx, s, acct, app, env) |
| + if err != nil { |
| + return time.Time{}, err |
| + } |
| + wc, etag, err := GetWriteCredentialsIn(ctx, s, acct, app, env) |
| + if err != nil { |
| + return time.Time{}, err |
| + } |
| + if wc == nil { |
| + return time.Time{}, ErrNoWriteCredentials |
| + } |
| + t := revocationInstant(wc, now) |
| + wc.RevokedBefore = &t |
| + if _, err := claimRawPutWriteCredentialsIn(ctx, s, acct, app, env, wc, etag); err != nil { |
| + return time.Time{}, fmt.Errorf("objstore: record revocation for %s/%s: %w", acct, app, err) |
| + } |
| + if err := claimRawConvergeWriterIn(ctx, s, p, acct, app, env, rec.Provisioned.Bucket); err != nil { |
| + return time.Time{}, err |
| + } |
| + return t, nil |
| +} |
| + |
| +// MintWriteCredentialIn is claimRawMintWriteCredentialIn inside the app |
| +// mutation, as every walk is. |
| +func MintWriteCredentialIn(ctx context.Context, s release.Store, p Provisioner, acct, app, env, by, prefix string, ttl time.Duration, now time.Time) (claimResult0 *WriteCredential, claimResult1 error) { |
| + claimResult1 = release.WithAppMutation(ctx, s, acct, app, "objstore.MintWriteCredentialIn", func(claimContext context.Context) error { |
| + claimResult0, claimResult1 = claimRawMintWriteCredentialIn(claimContext, s, p, acct, app, env, by, prefix, ttl, now) |
| + return claimResult1 |
| + }) |
| + return |
| +} |
| + |
| +// RevokeWriteCredentialsIn is claimRawRevokeWriteCredentialsIn inside the |
| +// app mutation. |
| +func RevokeWriteCredentialsIn(ctx context.Context, s release.Store, p Provisioner, acct, app, env string, now time.Time) (claimResult0 time.Time, claimResult1 error) { |
| + claimResult1 = release.WithAppMutation(ctx, s, acct, app, "objstore.RevokeWriteCredentialsIn", func(claimContext context.Context) error { |
| + claimResult0, claimResult1 = claimRawRevokeWriteCredentialsIn(claimContext, s, p, acct, app, env, now) |
| + return claimResult1 |
| + }) |
| + return |
| +} |
diff --git a/internal/objstore/writecred_policy_test.go b/internal/objstore/writecred_policy_test.go| new file mode 100644 |
| index 000000000..3d33d07d4 |
| --- /dev/null |
| +++ b/internal/objstore/writecred_policy_test.go |
| @@ -0,0 +1,323 @@ |
| +package objstore |
| + |
| +import ( |
| + "encoding/json" |
| + "path" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// A small IAM evaluator, enough to judge the documents this package writes |
| +// against the requests a write credential could make (spec §11). It knows |
| +// Allow and Deny, Action and NotAction, Resource and NotResource with IAM's |
| +// * and ? wildcards, and the condition operators these documents use: |
| +// StringEquals, ForAnyValue:StringEquals, Null and DateLessThan. A request |
| +// is allowed when no layer denies it and every identity layer allows it, or |
| +// when a resource policy naming the session allows it (AWS: a resource |
| +// policy naming a federated session can grant beyond the session policy). |
| + |
| +type iamRequest struct { |
| + action string |
| + resource string |
| + // keys is the request context: condition key to values. A key absent |
| + // from the map is absent from the request. |
| + keys map[string][]string |
| +} |
| + |
| +type iamStatement struct { |
| + Effect string `json:"Effect"` |
| + Action any `json:"Action"` |
| + NotAction any `json:"NotAction"` |
| + Resource any `json:"Resource"` |
| + NotResource any `json:"NotResource"` |
| + Condition map[string]map[string]any `json:"Condition"` |
| +} |
| + |
| +type iamDoc struct { |
| + Statement []iamStatement `json:"Statement"` |
| +} |
| + |
| +func parseIAM(t *testing.T, doc string) iamDoc { |
| + t.Helper() |
| + var d iamDoc |
| + if err := json.Unmarshal([]byte(doc), &d); err != nil { |
| + t.Fatalf("parse policy: %v\n%s", err, doc) |
| + } |
| + return d |
| +} |
| + |
| +func iamList(v any) []string { |
| + switch x := v.(type) { |
| + case nil: |
| + return nil |
| + case string: |
| + return []string{x} |
| + case []any: |
| + out := make([]string, len(x)) |
| + for i, e := range x { |
| + out[i] = e.(string) |
| + } |
| + return out |
| + case []string: |
| + return x |
| + } |
| + panic("iam: unexpected value") |
| +} |
| + |
| +// iamMatch is IAM's wildcard match: * any run, ? one character. Action |
| +// names are case-insensitive. |
| +func iamMatch(pattern, s string, fold bool) bool { |
| + if fold { |
| + pattern, s = strings.ToLower(pattern), strings.ToLower(s) |
| + } |
| + ok, err := path.Match(strings.ReplaceAll(pattern, "/", "\x00"), strings.ReplaceAll(s, "/", "\x00")) |
| + return err == nil && ok |
| +} |
| + |
| +func anyMatch(patterns []string, s string, fold bool) bool { |
| + for _, p := range patterns { |
| + if iamMatch(p, s, fold) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func (st iamStatement) applies(t *testing.T, r iamRequest) bool { |
| + if st.Action != nil && !anyMatch(iamList(st.Action), r.action, true) { |
| + return false |
| + } |
| + if st.NotAction != nil && anyMatch(iamList(st.NotAction), r.action, true) { |
| + return false |
| + } |
| + if st.Resource != nil && !anyMatch(iamList(st.Resource), r.resource, false) { |
| + return false |
| + } |
| + if st.NotResource != nil && anyMatch(iamList(st.NotResource), r.resource, false) { |
| + return false |
| + } |
| + for op, kv := range st.Condition { |
| + for key, want := range kv { |
| + got, present := r.keys[key] |
| + wants := iamList(want) |
| + switch op { |
| + case "StringEquals": |
| + if !present || !anyMatch(wants, got[0], false) { |
| + return false |
| + } |
| + case "ForAnyValue:StringEquals": |
| + hit := false |
| + for _, g := range got { |
| + for _, w := range wants { |
| + hit = hit || g == w |
| + } |
| + } |
| + if !hit { |
| + return false |
| + } |
| + case "Null": |
| + if (wants[0] == "true") == present { |
| + return false |
| + } |
| + case "DateLessThan": |
| + if !present { |
| + return false |
| + } |
| + g, err1 := time.Parse(time.RFC3339, got[0]) |
| + w, err2 := time.Parse(time.RFC3339, wants[0]) |
| + if err1 != nil || err2 != nil { |
| + t.Fatalf("DateLessThan on %q, %q", got[0], wants[0]) |
| + } |
| + if !g.Before(w) { |
| + return false |
| + } |
| + default: |
| + t.Fatalf("evaluator does not know condition operator %s", op) |
| + } |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func (d iamDoc) decide(t *testing.T, r iamRequest) (allow, deny bool) { |
| + for _, st := range d.Statement { |
| + if !st.applies(t, r) { |
| + continue |
| + } |
| + switch st.Effect { |
| + case "Allow": |
| + allow = true |
| + case "Deny": |
| + deny = true |
| + } |
| + } |
| + return |
| +} |
| + |
| +// evalIAM: identity layers must all allow; any layer's Deny wins; a |
| +// resource policy may allow on its own. |
| +func evalIAM(t *testing.T, r iamRequest, identity []iamDoc, resource *iamDoc) bool { |
| + all := true |
| + for _, d := range identity { |
| + allow, deny := d.decide(t, r) |
| + if deny { |
| + return false |
| + } |
| + all = all && allow |
| + } |
| + if resource != nil { |
| + allow, deny := resource.decide(t, r) |
| + if deny { |
| + return false |
| + } |
| + if allow { |
| + return true |
| + } |
| + } |
| + return all |
| +} |
| + |
| +// testStoreBoundary is region-host's store user boundary with |
| +// store_write_credentials on, transcribed for this test. The tofu test |
| +// (store_write_credentials.tftest.hcl) pins the module's own rendering. |
| +func testStoreBoundary() string { |
| + return `{"Version":"2012-10-17","Statement":[ |
| + {"Effect":"Allow","Action":["s3:ListBucket","s3:GetBucketLocation"],"Resource":"arn:aws:s3:::carlos-store-*"}, |
| + {"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":"arn:aws:s3:::carlos-store-*/*"}, |
| + {"Effect":"Allow","Action":["sts:GetFederationToken"],"Resource":"arn:aws:sts::123456789012:federated-user/carlos-write-*"}]}` |
| +} |
| + |
| +const ( |
| + evalBucket = "carlos-store-bab-titogo" |
| + evalPrefix = "recordings/" |
| +) |
| + |
| +// sessionLayers is what a write credential's request is judged against: |
| +// the boundary, the writer's policy, the session policy. |
| +func sessionLayers(t *testing.T, denyWrites bool, wc *WriteCredentials) []iamDoc { |
| + return []iamDoc{ |
| + parseIAM(t, testStoreBoundary()), |
| + parseIAM(t, writerPolicyJSON("arn:aws:s3:::"+evalBucket, denyWrites, wc)), |
| + parseIAM(t, writeSessionPolicy(evalBucket, evalPrefix)), |
| + } |
| +} |
| + |
| +func obj(bucket, key string) string { return "arn:aws:s3:::" + bucket + "/" + key } |
| + |
| +func TestWriteCredentialScopeEvaluation(t *testing.T) { |
| + issued := map[string][]string{"aws:TokenIssueTime": {"2026-11-25T10:00:00Z"}} |
| + withKeys := func(extra map[string][]string) map[string][]string { |
| + m := map[string][]string{"aws:TokenIssueTime": issued["aws:TokenIssueTime"]} |
| + for k, v := range extra { |
| + m[k] = v |
| + } |
| + return m |
| + } |
| + allowed := []iamRequest{ |
| + {"s3:PutObject", obj(evalBucket, "recordings/a.mp4"), issued}, |
| + {"s3:PutObject", obj(evalBucket, "recordings/2026/a.mp4"), issued}, |
| + {"s3:AbortMultipartUpload", obj(evalBucket, "recordings/a.mp4"), issued}, |
| + {"s3:ListMultipartUploadParts", obj(evalBucket, "recordings/a.mp4"), issued}, |
| + } |
| + denied := []iamRequest{ |
| + // read, list, delete |
| + {"s3:GetObject", obj(evalBucket, "recordings/a.mp4"), issued}, |
| + {"s3:GetObject", obj(evalBucket, "private/secret.txt"), issued}, |
| + {"s3:GetObjectVersion", obj(evalBucket, "recordings/a.mp4"), issued}, |
| + {"s3:ListBucket", "arn:aws:s3:::" + evalBucket, issued}, |
| + {"s3:ListBucketMultipartUploads", "arn:aws:s3:::" + evalBucket, issued}, |
| + {"s3:DeleteObject", obj(evalBucket, "recordings/a.mp4"), issued}, |
| + {"s3:DeleteObjectVersion", obj(evalBucket, "recordings/a.mp4"), issued}, |
| + // tags and ACLs |
| + {"s3:PutObjectTagging", obj(evalBucket, "recordings/a.mp4"), issued}, |
| + {"s3:GetObjectTagging", obj(evalBucket, "recordings/a.mp4"), issued}, |
| + {"s3:PutObjectAcl", obj(evalBucket, "recordings/a.mp4"), issued}, |
| + {"s3:PutObject", obj(evalBucket, "recordings/a.mp4"), withKeys(map[string][]string{"s3:RequestObjectTagKeys": {"colour"}})}, |
| + {"s3:PutObject", obj(evalBucket, "recordings/a.mp4"), withKeys(map[string][]string{"s3:RequestObjectTagKeys": {TagVerdict}})}, |
| + {"s3:PutObjectRetention", obj(evalBucket, "recordings/a.mp4"), issued}, |
| + // bucket calls |
| + {"s3:PutBucketPolicy", "arn:aws:s3:::" + evalBucket, issued}, |
| + {"s3:PutBucketCORS", "arn:aws:s3:::" + evalBucket, issued}, |
| + {"s3:DeleteBucket", "arn:aws:s3:::" + evalBucket, issued}, |
| + {"s3:GetBucketLocation", "arn:aws:s3:::" + evalBucket, issued}, |
| + // outside the prefix |
| + {"s3:PutObject", obj(evalBucket, "other/a.mp4"), issued}, |
| + {"s3:PutObject", obj(evalBucket, "recordings-private/a.mp4"), issued}, |
| + {"s3:PutObject", obj(evalBucket, "recordings"), issued}, |
| + {"s3:PutObject", obj(evalBucket, "derived/a/b.mp4"), issued}, |
| + {"s3:AbortMultipartUpload", obj(evalBucket, "other/a.mp4"), issued}, |
| + // another store, the deployment's buckets |
| + {"s3:PutObject", obj("carlos-store-bab-other", "recordings/a.mp4"), issued}, |
| + {"s3:PutObject", obj("carlos-store-zzz-titogo", "recordings/a.mp4"), issued}, |
| + {"s3:PutObject", obj("carlos-dev-640012953448", "recordings/a.mp4"), issued}, |
| + {"s3:PutObject", obj("carlos-data-ie-640012953448", "recordings/a.mp4"), issued}, |
| + // no STS or IAM from the session |
| + {"sts:GetFederationToken", "arn:aws:sts::123456789012:federated-user/carlos-write-x", issued}, |
| + {"iam:CreateAccessKey", "arn:aws:iam::123456789012:user/carlos-store/carlos-w-bab-titogo", issued}, |
| + } |
| + layers := sessionLayers(t, false, &WriteCredentials{}) |
| + for _, r := range allowed { |
| + if !evalIAM(t, r, layers, nil) { |
| + t.Errorf("write credential refused %s on %s", r.action, r.resource) |
| + } |
| + } |
| + for _, r := range denied { |
| + if evalIAM(t, r, layers, nil) { |
| + t.Errorf("write credential allowed %s on %s (%v)", r.action, r.resource, r.keys) |
| + } |
| + } |
| + |
| + // A resource policy naming the session and granting everything cannot |
| + // widen it: the session policy's explicit Denies win (astra 1.6). |
| + rp := parseIAM(t, `{"Statement":[{"Effect":"Allow","Action":"s3:*","Resource":["arn:aws:s3:::`+evalBucket+`","arn:aws:s3:::`+evalBucket+`/*"]}]}`) |
| + for _, r := range denied { |
| + if evalIAM(t, r, layers, &rp) { |
| + t.Errorf("a resource policy widened the write credential to %s on %s", r.action, r.resource) |
| + } |
| + } |
| + |
| + // Past the storage grace, the writer refuses uploads too. |
| + for _, r := range allowed { |
| + if r.action == "s3:PutObject" && evalIAM(t, r, sessionLayers(t, true, &WriteCredentials{}), nil) { |
| + t.Errorf("write credential uploaded %s past the storage grace", r.resource) |
| + } |
| + } |
| + |
| + // Revoked: a session issued before the instant is refused everything, |
| + // one issued after it keeps its scope. |
| + rb := time.Date(2026, 11, 25, 11, 0, 0, 0, time.UTC) |
| + revoked := sessionLayers(t, false, &WriteCredentials{RevokedBefore: &rb}) |
| + put := iamRequest{"s3:PutObject", obj(evalBucket, "recordings/a.mp4"), issued} |
| + if evalIAM(t, put, revoked, nil) { |
| + t.Error("a session issued before the revocation still uploads") |
| + } |
| + put.keys = map[string][]string{"aws:TokenIssueTime": {"2026-11-25T11:00:01Z"}} |
| + if !evalIAM(t, put, revoked, nil) { |
| + t.Error("a session issued after the revocation was refused") |
| + } |
| +} |
| + |
| +// Who may call GetFederationToken with long-term keys: the writer, for |
| +// session names under carlos-write-; never the app's own key (the store |
| +// user), which is what keeps every session in the console's hands. |
| +func TestOnlyTheWriterMintsSessions(t *testing.T) { |
| + boundary := parseIAM(t, testStoreBoundary()) |
| + writer := parseIAM(t, writerPolicyJSON("arn:aws:s3:::"+evalBucket, false, &WriteCredentials{})) |
| + store := parseIAM(t, storePolicyJSON("arn:aws:s3:::"+evalBucket, &DenyTag{Key: TagVerdict, Value: "infected"}, true)) |
| + ours := iamRequest{action: "sts:GetFederationToken", resource: "arn:aws:sts::123456789012:federated-user/carlos-write-0123456789abcdef"} |
| + other := iamRequest{action: "sts:GetFederationToken", resource: "arn:aws:sts::123456789012:federated-user/someone"} |
| + if !evalIAM(t, ours, []iamDoc{boundary, writer}, nil) { |
| + t.Error("the writer cannot mint a carlos-write- session") |
| + } |
| + if evalIAM(t, other, []iamDoc{boundary, writer}, nil) { |
| + t.Error("the writer can mint a session under another name") |
| + } |
| + if evalIAM(t, ours, []iamDoc{boundary, store}, nil) { |
| + t.Error("the app's own key can mint a federation session") |
| + } |
| + // The writer's long-term key, were it ever to leak, still reads nothing. |
| + if evalIAM(t, iamRequest{action: "s3:GetObject", resource: obj(evalBucket, "recordings/a.mp4")}, []iamDoc{boundary, writer}, nil) { |
| + t.Error("the writer itself can read the store") |
| + } |
| +} |
diff --git a/internal/objstore/writecred_test.go b/internal/objstore/writecred_test.go| new file mode 100644 |
| index 000000000..474859b8c |
| --- /dev/null |
| +++ b/internal/objstore/writecred_test.go |
| @@ -0,0 +1,498 @@ |
| +package objstore |
| + |
| +import ( |
| + "context" |
| + "crypto/ecdh" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestValidWritePrefix(t *testing.T) { |
| + ok := []string{ |
| + "recordings/", |
| + "recordings/2026/", |
| + "a/", |
| + "Live_Streams-1.0/raw/", |
| + strings.Repeat("a", 199) + "/", |
| + } |
| + for _, p := range ok { |
| + if err := ValidWritePrefix(p); err != nil { |
| + t.Errorf("ValidWritePrefix(%q) = %v, want nil", p, err) |
| + } |
| + } |
| + bad := []string{ |
| + "", // the whole store |
| + "/", // the whole store again |
| + "recordings", // would also match recordings-private/ |
| + "/recordings/", // leading slash |
| + "recordings//", // empty segment |
| + "./recordings/", // dot segment |
| + "recordings/../", // dot-dot segment |
| + "rec*/", // IAM wildcard |
| + "rec?/", // IAM wildcard |
| + "${aws:username}/", // policy variable |
| + "rec ordings/", // space |
| + "récordings/", // non-ASCII |
| + "rec\"/", // JSON-breaking |
| + "derived/", // media conversion's outputs |
| + "derived/x/", // under them |
| + strings.Repeat("a", 200) + "/", // 201 bytes |
| + } |
| + for _, p := range bad { |
| + if err := ValidWritePrefix(p); err == nil { |
| + t.Errorf("ValidWritePrefix(%q) = nil, want a refusal", p) |
| + } else if !errors.Is(err, ErrBadWritePrefix) { |
| + t.Errorf("ValidWritePrefix(%q) = %v, want ErrBadWritePrefix", p, err) |
| + } |
| + } |
| +} |
| + |
| +func TestValidWriteTTL(t *testing.T) { |
| + for _, d := range []time.Duration{15 * time.Minute, 4 * time.Hour, 24 * time.Hour} { |
| + if err := ValidWriteTTL(d); err != nil { |
| + t.Errorf("ValidWriteTTL(%v) = %v, want nil", d, err) |
| + } |
| + } |
| + for _, d := range []time.Duration{0, -time.Hour, 15*time.Minute - time.Second, 24*time.Hour + time.Second, 36 * time.Hour} { |
| + if err := ValidWriteTTL(d); !errors.Is(err, ErrBadWriteTTL) { |
| + t.Errorf("ValidWriteTTL(%v) = %v, want ErrBadWriteTTL", d, err) |
| + } |
| + } |
| + // Whole seconds only: STS takes DurationSeconds. |
| + if err := ValidWriteTTL(time.Hour + time.Millisecond); !errors.Is(err, ErrBadWriteTTL) { |
| + t.Errorf("ValidWriteTTL(1h1ms) = %v, want ErrBadWriteTTL", err) |
| + } |
| +} |
| + |
| +// TestWriteSessionPolicyShape pins the session policy byte for byte. It is |
| +// the scope every write credential gets, and the MinIO contract runs this |
| +// same document against a real policy engine. |
| +func TestWriteSessionPolicyShape(t *testing.T) { |
| + got := writeSessionPolicy("carlos-store-bab-titogo", "recordings/") |
| + r := "arn:aws:s3:::carlos-store-bab-titogo/recordings/*" |
| + w := `["s3:PutObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"]` |
| + want := `{"Version":"2012-10-17","Statement":[` + |
| + `{"Effect":"Allow","Action":` + w + `,"Resource":"` + r + `"},` + |
| + `{"Effect":"Deny","NotAction":` + w + `,"Resource":"*"},` + |
| + `{"Effect":"Deny","Action":` + w + `,"NotResource":"` + r + `"},` + |
| + `{"Effect":"Deny","Action":["s3:PutObject"],"Resource":"` + r + `","Condition":{"Null":{"s3:RequestObjectTagKeys":"false"}}}]}` |
| + if got != want { |
| + t.Fatalf("writeSessionPolicy =\n%s\nwant\n%s", got, want) |
| + } |
| + if len(got) > 2048 { |
| + t.Fatalf("session policy is %d bytes, over STS's 2,048", len(got)) |
| + } |
| +} |
| + |
| +// The longest prefix and bucket still fit STS's 2,048-character limit. |
| +func TestWriteSessionPolicyFitsSTSLimit(t *testing.T) { |
| + bucket := strings.Repeat("b", 63) |
| + prefix := strings.Repeat("a", 199) + "/" |
| + if n := len(writeSessionPolicy(bucket, prefix)); n > 2048 { |
| + t.Fatalf("longest session policy is %d bytes, over STS's 2,048", n) |
| + } |
| +} |
| + |
| +func TestWriterName(t *testing.T) { |
| + for store, want := range map[string]string{ |
| + UserNameIn("bab", "titogo", ""): "carlos-w-bab-titogo", |
| + UserNameIn("bab", "titogo", "live"): "carlos-w-bab-titogo-live", |
| + } { |
| + if got := WriterName(store); got != want { |
| + t.Errorf("WriterName(%q) = %q, want %q", store, got, want) |
| + } |
| + if len(WriterName(store)) >= len(store) { |
| + t.Errorf("writer name %q is not shorter than its store user %q", WriterName(store), store) |
| + } |
| + } |
| +} |
| + |
| +// The writer's policy, byte for byte at its plainest, then with the |
| +// storage-grace Deny and a revocation appended. |
| +func TestWriterPolicyShape(t *testing.T) { |
| + arn := "arn:aws:s3:::carlos-store-bab-titogo" |
| + o := arn + "/*" |
| + base := `{"Version":"2012-10-17","Statement":[` + |
| + `{"Effect":"Allow","Action":["s3:PutObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":"` + o + `"},` + |
| + `{"Effect":"Allow","Action":["sts:GetFederationToken"],"Resource":"*"},` + |
| + `{"Effect":"Deny","Action":["s3:PutObjectTagging","s3:DeleteObjectTagging","s3:PutObjectVersionTagging","s3:DeleteObjectVersionTagging"],"Resource":"` + o + `"},` + |
| + `{"Effect":"Deny","Action":["s3:PutObject"],"Resource":"` + o + `","Condition":{"ForAnyValue:StringEquals":{"s3:RequestObjectTagKeys":["carlos-scan","carlos-scan-version","carlos-scan-at"]}}},` + |
| + `{"Effect":"Deny","Action":["s3:DeleteObjectVersion","s3:PutObjectRetention","s3:PutObjectLegalHold","s3:BypassGovernanceRetention"],"Resource":"` + o + `"}` |
| + wc := &WriteCredentials{At: time.Now(), By: "m@example.com"} |
| + if got, want := writerPolicyJSON(arn, false, wc), base+`]}`; got != want { |
| + t.Fatalf("writer policy =\n%s\nwant\n%s", got, want) |
| + } |
| + rb := time.Date(2026, 11, 25, 11, 0, 0, 0, time.UTC) |
| + wc.RevokedBefore = &rb |
| + want := base + `,{"Effect":"Deny","Action":["s3:PutObject"],"Resource":"` + o + `"}` + |
| + `,{"Effect":"Deny","Action":["*"],"Resource":"*","Condition":{"DateLessThan":{"aws:TokenIssueTime":"2026-11-25T11:00:00Z"}}}]}` |
| + if got := writerPolicyJSON(arn, true, wc); got != want { |
| + t.Fatalf("denied and revoked writer policy =\n%s\nwant\n%s", got, want) |
| + } |
| + // It names the store's one bucket and nothing else in S3, and grants |
| + // no read, list or delete at all. |
| + for _, banned := range []string{"s3:GetObject", "s3:ListBucket", `"s3:DeleteObject"`, "s3:*", "s3:PutBucket", "s3:PutObjectAcl"} { |
| + if strings.Contains(want, banned) { |
| + t.Fatalf("writer policy mentions %s: %s", banned, want) |
| + } |
| + } |
| +} |
| + |
| +// IAM caps a user's inline policies at 2,048 characters together. The |
| +// writer has one, and at its largest it must still fit, or PutUserPolicy |
| +// fails exactly when a revocation or the storage-grace Deny matters. |
| +func TestWriterPolicyFitsIAMLimit(t *testing.T) { |
| + rb := time.Now() |
| + doc := writerPolicyJSON("arn:aws:s3:::"+strings.Repeat("b", 63), true, &WriteCredentials{RevokedBefore: &rb}) |
| + if len(doc) > 2048 { |
| + t.Fatalf("largest writer policy is %d characters, over IAM's 2,048", len(doc)) |
| + } |
| +} |
| + |
| +// writeFixture is a provisioned store, bab/titogo, on the in-memory |
| +// provisioner. |
| +func writeFixture(t *testing.T) (release.Store, *MemProvisioner, *ecdh.PublicKey) { |
| + t.Helper() |
| + s := release.NewDirStore(t.TempDir()) |
| + _, pub := testSealKeypair(t) |
| + p := NewMemProvisioner("eu-west-1") |
| + rotateFixture(t, s, pub, p) |
| + return s, p, pub |
| +} |
| + |
| +func mint(t *testing.T, s release.Store, p Provisioner, prefix string, ttl time.Duration, now time.Time) (*WriteCredential, error) { |
| + t.Helper() |
| + return MintWriteCredentialIn(context.Background(), s, p, "bab", "titogo", "", "m@example.com", prefix, ttl, now) |
| +} |
| + |
| +func TestMintWriteCredential(t *testing.T) { |
| + s, p, _ := writeFixture(t) |
| + storeUser := UserNameIn("bab", "titogo", "") |
| + storePolicy := p.PolicyFor(storeUser) |
| + now := time.Now().UTC() |
| + |
| + wc, err := mint(t, s, p, "recordings/", 4*time.Hour, now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec, _, _ := GetIn(context.Background(), s, "bab", "titogo", "") |
| + if wc.Bucket != rec.Provisioned.Bucket || wc.Region != "eu-west-1" || wc.Prefix != "recordings/" || |
| + wc.AccessKeyID == "" || wc.SecretAccessKey == "" || wc.SessionToken == "" || wc.Expires.Sub(wc.Issued) != 4*time.Hour { |
| + t.Fatalf("credential = %+v", wc) |
| + } |
| + // Minted as the writer, narrowed by the core's session policy. |
| + if len(p.Sessions) != 1 { |
| + t.Fatalf("%d sessions minted, want 1", len(p.Sessions)) |
| + } |
| + ms := p.Sessions[0] |
| + if ms.User != WriterName(storeUser) || ms.Policy != writeSessionPolicy(rec.Provisioned.Bucket, "recordings/") || ms.TTL != 4*time.Hour { |
| + t.Fatalf("session = %+v", ms) |
| + } |
| + // The writer exists with its policy and no key; the app's own user and |
| + // policy are untouched, and the app's user still cannot call STS. |
| + w, ok := p.Users[WriterName(storeUser)] |
| + if !ok || w.Policy != writerPolicyJSON("arn:aws:s3:::"+rec.Provisioned.Bucket, false, mustState(t, s)) || len(w.Keys) != 0 { |
| + t.Fatalf("writer = %+v", w) |
| + } |
| + if got := p.PolicyFor(storeUser); got != storePolicy || strings.Contains(got, "sts:") { |
| + t.Fatalf("store user's policy changed or names STS: %s", got) |
| + } |
| + if p.SingleUseKeys != 1 { |
| + t.Fatalf("%d single-use keys, want 1", p.SingleUseKeys) |
| + } |
| + st := mustState(t, s) |
| + if st.By != "m@example.com" || st.RevokedBefore != nil || st.Account != "bab" || st.App != "titogo" { |
| + t.Fatalf("state = %+v", st) |
| + } |
| + // A second mint reuses the state object, and its first-mint stamp. |
| + if _, err := mint(t, s, p, "recordings/2026/", time.Hour, now.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := mustState(t, s); !got.At.Equal(st.At) { |
| + t.Fatalf("second mint rewrote the first-mint time: %v, was %v", got.At, st.At) |
| + } |
| +} |
| + |
| +func mustState(t *testing.T, s release.Store) *WriteCredentials { |
| + t.Helper() |
| + wc, _, err := GetWriteCredentialsIn(context.Background(), s, "bab", "titogo", "") |
| + if err != nil || wc == nil { |
| + t.Fatalf("state object: %v, %v", wc, err) |
| + } |
| + return wc |
| +} |
| + |
| +func TestMintWriteCredentialRefusals(t *testing.T) { |
| + now := time.Now().UTC() |
| + t.Run("prefix", func(t *testing.T) { |
| + s, p, _ := writeFixture(t) |
| + if _, err := mint(t, s, p, "derived/", time.Hour, now); !errors.Is(err, ErrBadWritePrefix) { |
| + t.Fatalf("mint under derived/: %v", err) |
| + } |
| + assertNothingMinted(t, s, p) |
| + }) |
| + t.Run("ttl", func(t *testing.T) { |
| + s, p, _ := writeFixture(t) |
| + if _, err := mint(t, s, p, "recordings/", 48*time.Hour, now); !errors.Is(err, ErrBadWriteTTL) { |
| + t.Fatalf("mint for 48h: %v", err) |
| + } |
| + assertNothingMinted(t, s, p) |
| + }) |
| + t.Run("not provisioned", func(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + p := NewMemProvisioner("eu-west-1") |
| + declare(t, s, "bab", "titogo", "TITO_S3") |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, now); !errors.Is(err, ErrNotProvisioned) { |
| + t.Fatalf("mint on a declared store: %v", err) |
| + } |
| + assertNothingMinted(t, s, p) |
| + }) |
| + t.Run("endpoint", func(t *testing.T) { |
| + s, p, _ := writeFixture(t) |
| + rec, etag, _ := GetIn(context.Background(), s, "bab", "titogo", "") |
| + rec.Provisioned.Endpoint = "https://s3.example.com" |
| + if _, err := PutIn(context.Background(), s, "bab", "titogo", "", rec, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, now); !errors.Is(err, ErrWriteCredentialsUnsupported) { |
| + t.Fatalf("mint on an S3-compatible store: %v", err) |
| + } |
| + assertNothingMinted(t, s, p) |
| + }) |
| +} |
| + |
| +func assertNothingMinted(t *testing.T, s release.Store, p *MemProvisioner) { |
| + t.Helper() |
| + if len(p.Sessions) != 0 || p.WriterWrites != 0 { |
| + t.Fatalf("a refused mint minted %d sessions and wrote the writer %d times", len(p.Sessions), p.WriterWrites) |
| + } |
| + if wc, _, _ := GetWriteCredentialsIn(context.Background(), s, "bab", "titogo", ""); wc != nil { |
| + t.Fatalf("a refused mint wrote the state object: %+v", wc) |
| + } |
| +} |
| + |
| +// Paul, 2026-11-25: no refusal during a rotation. The writer is another |
| +// user, so the app's two key slots do not matter to it. |
| +func TestMintDuringUnfinishedRotation(t *testing.T) { |
| + s, p, pub := writeFixture(t) |
| + if _, err := Rotate(context.Background(), s, p, storeTestSealer(pub, "bab", "titogo"), "bab", "titogo", time.Now().UTC()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec, _, _ := GetIn(context.Background(), s, "bab", "titogo", ""); rec.Provisioned.PrevKeyID == "" { |
| + t.Fatal("fixture: rotation left no pending key") |
| + } |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, time.Now().UTC()); err != nil { |
| + t.Fatalf("mint during an unfinished rotation: %v", err) |
| + } |
| + if n := len(p.Users[UserNameIn("bab", "titogo", "")].Keys); n != 2 { |
| + t.Fatalf("the mint touched the app's keys: %d left, want 2", n) |
| + } |
| +} |
| + |
| +// A key a crashed mint left on the writer is reaped by the next mint. |
| +func TestMintReapsStrayWriterKeys(t *testing.T) { |
| + s, p, _ := writeFixture(t) |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, time.Now().UTC()); err != nil { |
| + t.Fatal(err) |
| + } |
| + writer := WriterName(UserNameIn("bab", "titogo", "")) |
| + p.Users[writer].Keys["STRAY1"] = "lost" |
| + p.Users[writer].Keys["STRAY2"] = "lost" |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, time.Now().UTC()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := len(p.Users[writer].Keys); n != 0 { |
| + t.Fatalf("writer holds %d keys after a mint, want 0", n) |
| + } |
| +} |
| + |
| +func TestRevokeWriteCredentials(t *testing.T) { |
| + ctx := context.Background() |
| + s, p, _ := writeFixture(t) |
| + now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC) |
| + if _, err := RevokeWriteCredentialsIn(ctx, s, p, "bab", "titogo", "", now); !errors.Is(err, ErrNoWriteCredentials) { |
| + t.Fatalf("revoke before any mint: %v", err) |
| + } |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + rb, err := RevokeWriteCredentialsIn(ctx, s, p, "bab", "titogo", "", now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // ε past the console's clock, rounded up to the second. |
| + if want := now.Add(clockBound + time.Second); !rb.Equal(want) { |
| + t.Fatalf("revoked before %v, want %v", rb, want) |
| + } |
| + rec, _, _ := GetIn(ctx, s, "bab", "titogo", "") |
| + writer := WriterName(UserNameIn("bab", "titogo", "")) |
| + if got, want := p.Users[writer].Policy, writerPolicyJSON("arn:aws:s3:::"+rec.Provisioned.Bucket, false, mustState(t, s)); got != want || |
| + !strings.Contains(got, `"aws:TokenIssueTime":"`+rb.Format(time.RFC3339)+`"`) { |
| + t.Fatalf("writer policy after revoke:\n%s", got) |
| + } |
| + // Never moves earlier. |
| + if rb2, err := RevokeWriteCredentialsIn(ctx, s, p, "bab", "titogo", "", now.Add(-time.Hour)); err != nil || !rb2.Equal(rb) { |
| + t.Fatalf("an earlier revoke moved the instant: %v, %v", rb2, err) |
| + } |
| +} |
| + |
| +// Mints after a revocation, by both clocks (spec §2.4): refused while the |
| +// console's clock is inside the margin, and refused by AWS's own issue time |
| +// when the console runs ahead of AWS. Allowed once both are clear. |
| +func TestMintAfterRevocationClocks(t *testing.T) { |
| + ctx := context.Background() |
| + s, p, _ := writeFixture(t) |
| + t0 := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC) |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, t0); err != nil { |
| + t.Fatal(err) |
| + } |
| + rb, err := RevokeWriteCredentialsIn(ctx, s, p, "bab", "titogo", "", t0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var settling *RevocationSettlingError |
| + |
| + // Inside the console-side holdoff: refused before any session. |
| + before := len(p.Sessions) |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, rb.Add(clockBound-time.Second)); !errors.As(err, &settling) { |
| + t.Fatalf("mint inside the holdoff: %v", err) |
| + } |
| + if len(p.Sessions) != before { |
| + t.Fatal("a mint inside the holdoff minted a session") |
| + } |
| + |
| + // Console clear of the holdoff but more than ε ahead of AWS: AWS says |
| + // the session was issued before the revocation, so it is discarded. |
| + consoleNow := rb.Add(clockBound) |
| + p.AWSClock = func() time.Time { return rb.Add(-2 * time.Second) } |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, consoleNow); !errors.As(err, &settling) { |
| + t.Fatalf("mint whose AWS issue time is before the revocation: %v", err) |
| + } |
| + if !settling.Until.After(consoleNow) { |
| + t.Fatalf("settling until %v, not after now %v", settling.Until, consoleNow) |
| + } |
| + // Within the one-second rounding: still refused. |
| + p.AWSClock = func() time.Time { return rb.Add(500 * time.Millisecond) } |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, consoleNow); !errors.As(err, &settling) { |
| + t.Fatalf("mint issued half a second after the revocation: %v", err) |
| + } |
| + // Console behind AWS: AWS's issue time is clear, so the mint stands. |
| + p.AWSClock = func() time.Time { return rb.Add(90 * time.Second) } |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, consoleNow); err != nil { |
| + t.Fatalf("mint after the revocation by both clocks: %v", err) |
| + } |
| +} |
| + |
| +// The storage-grace Deny reaches the writer through the grant walk, which |
| +// is how storage-limit convergence applies it. |
| +func TestGrantConvergesWriterPolicy(t *testing.T) { |
| + ctx := context.Background() |
| + s, p, pub := writeFixture(t) |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, time.Now().UTC()); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec, etag, _ := GetIn(ctx, s, "bab", "titogo", "") |
| + rec.WritesDenied = &WritesDenied{Reason: "storage", At: time.Now().UTC()} |
| + if _, err := PutIn(ctx, s, "bab", "titogo", "", rec, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := Grant(ctx, s, p, testDeployment(), storeTestSealer(pub, "bab", "titogo"), "bab", "titogo", "op", GrantSourceOperator, "", time.Now().UTC()); err != nil { |
| + t.Fatal(err) |
| + } |
| + writer := WriterName(UserNameIn("bab", "titogo", "")) |
| + if got, want := p.Users[writer].Policy, writerPolicyJSON("arn:aws:s3:::"+rec.Provisioned.Bucket, true, mustState(t, s)); got != want { |
| + t.Fatalf("writer policy after a grant with writes denied:\n%s\nwant\n%s", got, want) |
| + } |
| + // A store with no writer gets none from a grant. |
| + s2, p2, pub2 := writeFixture(t) |
| + if _, err := Grant(ctx, s2, p2, testDeployment(), storeTestSealer(pub2, "bab", "titogo"), "bab", "titogo", "op", GrantSourceOperator, "", time.Now().UTC()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := p2.Users[writer]; ok || p2.WriterWrites != 0 { |
| + t.Fatal("a grant made a writer for a store that never minted") |
| + } |
| +} |
| + |
| +// Write-then-validate (spec §2.3): a revocation that lands between a grant |
| +// walk's read and its policy write must not be lost. The grant's write is |
| +// computed from the old state; the revocation happens right after it; the |
| +// validation reads the new state and writes again. |
| +func TestWriterPolicySurvivesRacingRevoke(t *testing.T) { |
| + ctx := context.Background() |
| + s, p, _ := writeFixture(t) |
| + now := time.Now().UTC() |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec, _, _ := GetIn(ctx, s, "bab", "titogo", "") |
| + bucket := rec.Provisioned.Bucket |
| + raced := false |
| + p.AfterEnsureWriter = func(string) { |
| + if raced { |
| + return |
| + } |
| + raced = true |
| + // The revocation's own state write, as a racing revoke door makes |
| + // it before its policy write. |
| + wc, etag, err := GetWriteCredentialsIn(ctx, s, "bab", "titogo", "") |
| + if err != nil { |
| + t.Error(err) |
| + return |
| + } |
| + rb := now.Add(time.Hour) |
| + wc.RevokedBefore = &rb |
| + if _, err := claimRawPutWriteCredentialsIn(ctx, s, "bab", "titogo", "", wc, etag); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + if err := claimRawConvergeWriterIn(ctx, s, p, "bab", "titogo", "", bucket); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !raced { |
| + t.Fatal("the race never ran") |
| + } |
| + writer := WriterName(UserNameIn("bab", "titogo", "")) |
| + if got := p.Users[writer].Policy; !strings.Contains(got, "aws:TokenIssueTime") { |
| + t.Fatalf("the racing revocation was lost: %s", got) |
| + } |
| +} |
| + |
| +func TestTeardownRemovesWriter(t *testing.T) { |
| + ctx := context.Background() |
| + s, p, _ := writeFixture(t) |
| + if _, err := mint(t, s, p, "recordings/", time.Hour, time.Now().UTC()); err != nil { |
| + t.Fatal(err) |
| + } |
| + writer := WriterName(UserNameIn("bab", "titogo", "")) |
| + p.Users[writer].Keys["STRAY"] = "lost" |
| + if err := Teardown(ctx, s, p, nil, "bab", "titogo"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := p.Users[writer]; ok { |
| + t.Fatal("teardown left the writer user") |
| + } |
| + if wc, _, err := GetWriteCredentialsIn(ctx, s, "bab", "titogo", ""); err != nil || wc != nil { |
| + t.Fatalf("teardown left the state object: %+v, %v", wc, err) |
| + } |
| +} |
| + |
| +// The state object refuses a body that names another store. |
| +func TestWriteCredentialsStateMismatch(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + body, _ := json.Marshal(WriteCredentials{Schema: 1, Account: "zzz", App: "titogo"}) |
| + if _, err := s.Put(ctx, WriteCredentialsKey("bab", "titogo", ""), body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _, err := GetWriteCredentialsIn(ctx, s, "bab", "titogo", ""); !errors.Is(err, ErrWriteCredentialsMismatch) { |
| + t.Fatalf("mismatched state object: %v", err) |
| + } |
| + if got := WriteCredentialsKey("bab", "titogo", "live"); strings.HasPrefix(got, StoresPrefix("bab", "titogo")) { |
| + t.Fatalf("an environment's state object %s is under the stores collection", got) |
| + } |
| +} |