Skip to content
This repository has been archived by the owner on Oct 21, 2024. It is now read-only.

Commit

Permalink
sst.aws.Nextjs: use new resource.enc system for links
Browse files Browse the repository at this point in the history
  • Loading branch information
thdxr committed Oct 15, 2024
1 parent 88572b0 commit 7eefd24
Show file tree
Hide file tree
Showing 8 changed files with 112 additions and 77 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/binary.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
name: binary

on:
workflow_dispatch:
push:
workflow_dispatch:
tags:
- "*"

Expand Down Expand Up @@ -33,7 +33,7 @@ jobs:

- uses: actions/setup-go@v5
with:
go-version: ">=1.21.0"
go-version: ">=1.23.2"

- name: Go Mod
run: go mod download
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
name: build

on:
workflow_dispatch:
push:
workflow_dispatch:
branches:
- dev

Expand Down Expand Up @@ -33,7 +33,7 @@ jobs:

- uses: actions/setup-go@v5
with:
go-version: ">=1.21.0"
go-version: ">=1.23.2"

- name: Go Mod
run: go mod download
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/sst/ion

go 1.21.3
go 1.23.2

require (
github.com/Masterminds/semver/v3 v3.2.1
Expand Down
32 changes: 24 additions & 8 deletions pkg/runtime/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ type BuildInput struct {
Dev bool `json:"dev"`
FunctionID string `json:"functionID"`
Handler string `json:"handler"`
Bundle string `json:"bundle"`
Runtime string `json:"runtime"`
Properties json.RawMessage `json:"properties"`
Links map[string]json.RawMessage `json:"links"`
Expand Down Expand Up @@ -97,16 +98,31 @@ func (c *Collection) Build(ctx context.Context, input *BuildInput) (*BuildOutput
return nil, fmt.Errorf("Runtime not found: %v", input.Runtime)
}
out := input.Out()
if err := os.RemoveAll(out); err != nil {
return nil, err
}
if err := os.MkdirAll(out, 0755); err != nil {
return nil, err
var result *BuildOutput

if input.Bundle != "" {
out = input.Bundle
result = &BuildOutput{
Handler: input.Handler,
Errors: []string{},
}
}
result, err := runtime.Build(ctx, input)
if err != nil {
return nil, err

if input.Bundle == "" {
err := os.RemoveAll(out)
if err != nil {
return nil, err
}
err = os.MkdirAll(out, 0755)
if err != nil {
return nil, err
}
result, err = runtime.Build(ctx, input)
if err != nil {
return nil, err
}
}

result.Out = out

if len(input.CopyFiles) > 0 {
Expand Down
47 changes: 19 additions & 28 deletions platform/src/components/aws/function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1311,10 +1311,8 @@ export class Function extends Component implements Link.Linkable {
name: $app.name,
stage: $app.stage,
});
if (!bundle) {
result.SST_KEY = key;
result.SST_KEY_FILE = "resource.enc";
}
result.SST_KEY = key;
result.SST_KEY_FILE = "resource.enc";
if (dev) {
result.SST_REGION = process.env.SST_AWS_REGION!;
result.SST_FUNCTION_ID = name;
Expand Down Expand Up @@ -1487,13 +1485,6 @@ export class Function extends Component implements Link.Linkable {
};
}

if (args.bundle) {
return {
bundle: output(args.bundle),
handler: output(args.handler),
};
}

const buildResult = buildInput.apply(async (input) => {
const result = await rpc.call<{
handler: string;
Expand Down Expand Up @@ -1537,20 +1528,8 @@ export class Function extends Component implements Link.Linkable {
}

const hasUserInjections = injections.length > 0;
// already injected via esbuild when bundle is undefined
const hasLinkInjections = args.bundle && linkData.length > 0;

if (!hasUserInjections && !hasLinkInjections) return { handler };

const linkInjection = hasLinkInjections
? linkData
.map((item) => [
`process.env["SST_RESOURCE_${item.name}"] = ${JSON.stringify(
JSON.stringify(item.properties),
)};\n`,
])
.join("")
: "";
if (!hasUserInjections) return { handler };

const parsed = path.posix.parse(handler);
const handlerDir = parsed.dir;
Expand All @@ -1570,6 +1549,18 @@ export class Function extends Component implements Link.Linkable {
`Could not find handler file "${handler}" for function "${name}"`,
);

const split = injections.reduce(
(acc, item) => {
if (item.startsWith("outer:")) {
acc.outer.push(item.substring("outer:".length));
return acc;
}
acc.inner.push(item);
return acc;
},
{ outer: [] as string[], inner: [] as string[] },
);

return {
handler: path.posix.join(
handlerDir,
Expand All @@ -1579,17 +1570,17 @@ export class Function extends Component implements Link.Linkable {
name: path.posix.join(handlerDir, `${newHandlerFileName}.mjs`),
content: streaming
? [
linkInjection,
...split.outer,
`export const ${newHandlerFunction} = awslambda.streamifyResponse(async (event, responseStream, context) => {`,
...injections,
...split.inner,
` const { ${oldHandlerFunction}: rawHandler} = await import("./${oldHandlerFileName}${newHandlerFileExt}");`,
` return rawHandler(event, responseStream, context);`,
`});`,
].join("\n")
: [
linkInjection,
...split.outer,
`export const ${newHandlerFunction} = async (event, context) => {`,
...injections,
...split.inner,
` const { ${oldHandlerFunction}: rawHandler} = await import("./${oldHandlerFileName}${newHandlerFileExt}");`,
` return rawHandler(event, context);`,
`};`,
Expand Down
83 changes: 51 additions & 32 deletions platform/src/components/aws/nextjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -596,9 +596,9 @@ export class Nextjs extends Component implements Link.Linkable {
if (buildCommand) return buildCommand;
const version = openNextVersion ?? DEFAULT_OPEN_NEXT_VERSION;
const packageName = getOpenNextPackage(version);

return `npx --yes ${packageName}@${version} build`;
}
},
);
}

Expand Down Expand Up @@ -789,41 +789,60 @@ export class Nextjs extends Component implements Link.Linkable {
},
...(revalidationQueueArn
? [
{
actions: [
"sqs:SendMessage",
"sqs:GetQueueAttributes",
"sqs:GetQueueUrl",
],
resources: [revalidationQueueArn],
},
]
{
actions: [
"sqs:SendMessage",
"sqs:GetQueueAttributes",
"sqs:GetQueueUrl",
],
resources: [revalidationQueueArn],
},
]
: []),
...(revalidationTableArn
? [
{
actions: [
"dynamodb:BatchGetItem",
"dynamodb:GetRecords",
"dynamodb:GetShardIterator",
"dynamodb:Query",
"dynamodb:GetItem",
"dynamodb:Scan",
"dynamodb:ConditionCheckItem",
"dynamodb:BatchWriteItem",
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"dynamodb:DescribeTable",
],
resources: [
revalidationTableArn,
`${revalidationTableArn}/*`,
],
},
]
{
actions: [
"dynamodb:BatchGetItem",
"dynamodb:GetRecords",
"dynamodb:GetShardIterator",
"dynamodb:Query",
"dynamodb:GetItem",
"dynamodb:Scan",
"dynamodb:ConditionCheckItem",
"dynamodb:BatchWriteItem",
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"dynamodb:DescribeTable",
],
resources: [
revalidationTableArn,
`${revalidationTableArn}/*`,
],
},
]
: []),
],
injections: [
[
`outer:if (process.env.SST_KEY_FILE) {`,
` const { readFileSync } = await import("fs")`,
` const { createDecipheriv } = await import("crypto")`,
` const key = Buffer.from(process.env.SST_KEY, "base64");`,
` const encryptedData = readFileSync(process.env.SST_KEY_FILE);`,
` const nonce = Buffer.alloc(12, 0);`,
` const decipher = createDecipheriv("aes-256-gcm", key, nonce);`,
` const authTag = encryptedData.slice(-16);`,
` const actualCiphertext = encryptedData.slice(0, -16);`,
` decipher.setAuthTag(authTag);`,
` let decrypted = decipher.update(actualCiphertext);`,
` decrypted = Buffer.concat([decrypted, decipher.final()]);`,
` const decryptedData = JSON.parse(decrypted.toString());`,
` globalThis.SST_KEY_FILE_DATA = decryptedData;`,
`}`,
].join("\n"),
],
};

return validatePlan({
Expand Down
9 changes: 6 additions & 3 deletions platform/src/components/aws/ssr-site.ts
Original file line number Diff line number Diff line change
Expand Up @@ -750,9 +750,12 @@ export function createServersAndDistribution(
...(permissions ?? []),
...(props.function.permissions ?? []),
]),
injections: args.warm
? [useServerFunctionWarmingInjection(props.function.streaming)]
: [],
injections: [
...(args.warm
? [useServerFunctionWarmingInjection(props.function.streaming)]
: []),
...(props.function.injections || []),
],
link: output(args.link).apply((link) => [
...(props.function.link ?? []),
...(link ?? []),
Expand Down
8 changes: 7 additions & 1 deletion sdk/js/src/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ for (const [key, value] of Object.entries(environment)) {
}
}

if (env.SST_KEY_FILE && env.SST_KEY) {
// @ts-expect-error
if (env.SST_KEY_FILE && env.SST_KEY && !globalThis.SST_KEY_FILE_DATA) {
const key = Buffer.from(env.SST_KEY, "base64");
const encryptedData = readFileSync(env.SST_KEY_FILE);
const nonce = Buffer.alloc(12, 0);
Expand All @@ -39,6 +40,11 @@ if (env.SST_KEY_FILE && env.SST_KEY) {
Object.assign(raw, decryptedData);
}

// @ts-expect-error
if (globalThis.SST_KEY_FILE_DATA) {
// @ts-expect-error
Object.assign(raw, globalThis.SST_KEY_FILE_DATA);
}
export function fromCloudflareEnv(input: any) {
for (let [key, value] of Object.entries(input)) {
if (typeof value === "string") {
Expand Down

0 comments on commit 7eefd24

Please sign in to comment.