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
22 changes: 21 additions & 1 deletion pkg/runtime/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,27 @@ func (c *Collection) Build(ctx context.Context, input *BuildInput) (*BuildOutput
return nil, err
}
ciphertext := gcm.Seal(nil, make([]byte, 12), json, nil)
err = os.WriteFile(filepath.Join(result.Out, "resource.enc"), ciphertext, 0644)
// When a shared bundle is used, multiple functions share the same output
// directory (result.Out == input.Bundle). Writing "resource.enc" from
// concurrent Runtime.Build calls races: partial writes can leave a
// truncated or mixed ciphertext that fails AES-GCM authentication on
// the Lambda's first cold start (observed as `Decipheriv` errors at
// runtime initialization).
//
// Namespace the file under a per-function subdirectory so each function
// writes to its own path (eliminating the race) AND each function's
// uploaded zip can exclude every sibling's subtree (the .sst/ prefix
// gives a single, stable glob target for the zipper to filter on). The
// Lambda reads its own file via SST_KEY_FILE, which the platform
// component points at the matching path.
resourcePath := filepath.Join(result.Out, "resource.enc")
if input.Bundle != "" {
resourcePath = filepath.Join(result.Out, ".sst", input.FunctionID, "resource.enc")
if err := os.MkdirAll(filepath.Dir(resourcePath), 0755); err != nil {
return nil, err
}
}
err = os.WriteFile(resourcePath, ciphertext, 0644)
if err != nil {
return nil, err
}
Expand Down
66 changes: 66 additions & 0 deletions pkg/runtime/runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package runtime_test

import (
"context"
"encoding/base64"
"encoding/json"
"os"
"path/filepath"
"testing"

Expand Down Expand Up @@ -80,3 +83,66 @@ func TestCollectionRuntime(t *testing.T) {
assert.False(t, ok)
})
}

func TestCollectionBuildEncryptedResourceFileWithBundle(t *testing.T) {
// A 32-byte AES-256 key (all zeroes is fine for testing purposes).
encryptionKey := base64.StdEncoding.EncodeToString(make([]byte, 32))

t.Run("writes per-function subdirectory when bundle is set", func(t *testing.T) {
bundleDir := t.TempDir()

mr := &mockRuntime{matchFn: func(r string) bool { return r == "nodejs" }}
c := runtime.NewCollection("cfg", mr)

input := &runtime.BuildInput{
FunctionID: "my-function",
Handler: "index.handler",
Bundle: bundleDir,
Runtime: "nodejs",
EncryptionKey: encryptionKey,
Links: map[string]json.RawMessage{},
}

_, err := c.Build(context.Background(), input)
require.NoError(t, err)

// Per-function file lives under .sst/<FunctionID>/ so concurrent
// Build calls sharing the same bundle directory don't race, and the
// uploaded zip for each function can exclude every sibling's subtree.
perFunctionPath := filepath.Join(bundleDir, ".sst", "my-function", "resource.enc")
_, err = os.Stat(perFunctionPath)
assert.NoError(t, err, "expected %s to exist", perFunctionPath)

// Default top-level filename is reserved for the non-bundle
// (per-function artifact directory) path.
defaultPath := filepath.Join(bundleDir, "resource.enc")
_, err = os.Stat(defaultPath)
assert.True(t, os.IsNotExist(err), "default resource.enc should not exist when bundle is set")
})

t.Run("distinct functions sharing a bundle write to distinct subdirs", func(t *testing.T) {
bundleDir := t.TempDir()

mr := &mockRuntime{matchFn: func(r string) bool { return r == "nodejs" }}
c := runtime.NewCollection("cfg", mr)

for _, id := range []string{"fn-a", "fn-b"} {
input := &runtime.BuildInput{
FunctionID: id,
Handler: "index.handler",
Bundle: bundleDir,
Runtime: "nodejs",
EncryptionKey: encryptionKey,
Links: map[string]json.RawMessage{},
}
_, err := c.Build(context.Background(), input)
require.NoError(t, err)
}

for _, id := range []string{"fn-a", "fn-b"} {
p := filepath.Join(bundleDir, ".sst", id, "resource.enc")
_, err := os.Stat(p)
assert.NoError(t, err, "expected %s to exist", p)
}
})
}
34 changes: 31 additions & 3 deletions platform/src/components/aws/function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1896,8 +1896,9 @@ export class Function extends Component implements Link.Linkable {
Function.encryptionKey().base64,
args.link,
args.streaming,
args.bundle,
dev.apply((dev) => dev ? Function.appsync() : undefined),
]).apply(([environment, dev, bootstrap, key, link, streaming, appsync]) => {
]).apply(([environment, dev, bootstrap, key, link, streaming, bundle, appsync]) => {
const result = environment ?? {};
result.SST_RESOURCE_App = JSON.stringify({
name: $app.name,
Expand All @@ -1911,7 +1912,16 @@ export class Function extends Component implements Link.Linkable {
}
}
result.SST_KEY = key;
result.SST_KEY_FILE = "resource.enc";
// When a shared `bundle` is used, multiple functions write into the
// same output directory — the Go runtime namespaces the encrypted
// resource file under `.sst/<FunctionID>/resource.enc` to avoid a
// concurrent-write race that corrupts the ciphertext, AND so each
// Lambda's uploaded zip can exclude every sibling's subtree (the
// zipper filters on `.sst/<otherFunctionID>/`). Point each Lambda
// at its own file to match.
result.SST_KEY_FILE = bundle
? `.sst/${name}/resource.enc`
: "resource.enc";
if (dev) {
result.SST_REGION = process.env.SST_AWS_REGION!;
result.SST_APPSYNC_HTTP = appsync.http;
Expand Down Expand Up @@ -2495,8 +2505,26 @@ export class Function extends Component implements Link.Linkable {
sourcemaps?.map((item) => path.relative(bundle, item)) ||
[],
});
// When several functions share a `bundle:` directory the Go
// runtime writes per-function encrypted envelopes under
// `.sst/<FunctionID>/resource.enc`. Each Lambda must ship
// ONLY its own envelope — siblings' envelopes are encrypted
// with the same app-level key, so leaving them in the zip
// would expose every other Lambda's linked secrets/URLs to
// this one. Applies to the bundle iteration only; copyFiles
// entries can't contain a `.sst/<id>/` subtree.
const sstDir = `.sst${path.sep}`;
const ownDir = `.sst${path.sep}${name}${path.sep}`;
const filtered =
item.from === bundle
? found.filter(
(file) =>
!file.startsWith(sstDir) ||
file.startsWith(ownDir),
)
: found;
files.push(
...found.map((file) => ({
...filtered.map((file) => ({
from: path.join(item.from, file),
to: path.join(item.to, file),
})),
Expand Down