π₯ Make videos programmatically with React
added permissions validation
Matt McGillivrayb8841b8a5637
diff --git a/packages/docs/components/TableOfContents/api.tsx b/packages/docs/components/TableOfContents/api.tsxindex f793d1e982..eb2aa5ee41 100644--- a/packages/docs/components/TableOfContents/api.tsx+++ b/packages/docs/components/TableOfContents/api.tsx@@ -40,6 +40,10 @@ export const TableOfContents: React.FC = () => {<strong>@remotion/lambda</strong><div>Render videos and stills on AWS Lambda</div></TOCItem>+ <TOCItem link="/docs/gcp">+ <strong>@remotion/gcp</strong>+ <div>Render videos and stills on GCP Cloud Run</div>+ </TOCItem><TOCItem link="/docs/gif"><strong>@remotion/gif</strong><div>Include a GIF in your video</div>diff --git a/packages/docs/docs/gcp/cli.md b/packages/docs/docs/gcp/cli.mdnew file mode 100644index 0000000000..c11d909dfd--- /dev/null+++ b/packages/docs/docs/gcp/cli.md@@ -0,0 +1,29 @@+---+image: /generated/articles-docs-gcp-cli.png+id: cli+sidebar_label: Overview+title: "@remotion/gcp - CLI"+slug: /gcp/cli+---++To use the Remotion GCP CLI, you first need to [install it](/docs/gcp/setup).++## Commands++- [sites](/docs/gcp/cli/sites)+- [functions](/docs/gcp/cli/functions)+- [render](/docs/gcp/cli/render)+- [still](/docs/gcp/cli/still)+- [compositions](/docs/gcp/cli/compositions)+- [policies](/docs/gcp/cli/policies)+- [quotas](/docs/gcp/cli/quotas)++## Global options++### `--yes`, `-y`++Skips confirmation when doing a destructive action.++### `--quiet`, `-q`++Prints the minimal amount of logs.diff --git a/packages/docs/docs/gcp/region-selection.md b/packages/docs/docs/gcp/region-selection.mdindex fc207006d5..feabcfb96b 100644--- a/packages/docs/docs/gcp/region-selection.md+++ b/packages/docs/docs/gcp/region-selection.md@@ -18,7 +18,7 @@ The following GCP regions are available:<GcpRegionList />-You can call [`getRegions()`](/docs/gcp/getregions) or type [`npx remotion gcp regions`](/docs/lamgcpda/cli/regions) to get this list programmatically.+You can call [`getRegions()`](/docs/gcp/getregions) or type [`npx remotion gcp regions`](/docs/gcp/cli/regions) to get this list programmatically.## Default regiondiff --git a/packages/docs/docs/gcp/setup.md b/packages/docs/docs/gcp/setup.mdnew file mode 100644index 0000000000..a79689a549--- /dev/null+++ b/packages/docs/docs/gcp/setup.md@@ -0,0 +1,418 @@+---+image: /generated/articles-docs-gcp-setup.png+id: setup+title: Setup+slug: /gcp/setup+crumb: "Gcp"+---++import Tabs from '@theme/Tabs';+import TabItem from '@theme/TabItem';++## 1. Install `@remotion/gcp`++<Tabs+defaultValue="npm"+values={[+{ label: 'npm', value: 'npm', },+{ label: 'yarn', value: 'yarn', },+{ label: 'pnpm', value: 'pnpm', },+]+}>+<TabItem value="npm">++```bash+npm i @remotion/gcp+```++ </TabItem>++ <TabItem value="pnpm">++```bash+pnpm i @remotion/gcp+```++ </TabItem>+ <TabItem value="yarn">++```bash+yarn add @remotion/gcp+```++ </TabItem>++</Tabs>++Also update **all the other Remotion packages** to have the same version: `remotion`, `@remotion/cli` and others.++:::note+Make sure no package version number has a `^` character in front of it as it can lead to a version conflict.+:::++Your package.json should look like the following:++```json+ "@remotion/cli": "3.0.0", // Replace 3.0.0 with the current version+ "@remotion/gcp": "3.0.0", // Remove any `^` character+ // ...+ "remotion": "3.0.0",+```++## 2. Create a GCP project++Navigate to the [Manage Resources](https://console.cloud.google.com/cloud-resource-manager?walkthrough_id=resource-manager--create-project&start_index=1#step_index=1) screen in Google Cloud Console.++- On the Select organization drop-down list at the top of the page, select the organization resource in which you want to create a project. If you are a free trial user, skip this step, as this list does not appear.+- Click Create Project.+- In the New Project window that appears, enter a project name and select a billing account as applicable. A project name can contain only letters, numbers, single quotes, hyphens, spaces, or exclamation points, and must be between 4 and 30 characters.+- Enter the parent organization or folder resource in the Location box. That resource will be the hierarchical parent of the new project. If No organization is an option, you can select it to create your new project as the top level of its own resource hierarchy.+- When you're finished entering new project details, click Create.++## 3. Enable billing in the GCP Project++In order to enable the Cloud Run API, billing must be enabled in this project. Navigate to the [Billing](https://console.cloud.google.com/billing) screen in Google Cloud Console. Follow the on-screen prompts to create a billing account, and then link the new project to this billing account.++## 4. Setup Permissions / APIs / Service Account in GCP++_Note, this process does not require an understanding of Terraform._+[Google Cloud Shell](https://cloud.google.com/shell) is a browser-based command-line interface (CLI) for managing resources and applications hosted on GCP. It provides a virtual machine with pre-installed command-line tools and utilities, including the Google Cloud SDK and Terraform.++Google Cloud Shell is fully integrated with GCP, which means that you can access your projects, resources, and services directly from the command line without having to switch between multiple interfaces. Additionally, Cloud Shell offers a persistent disk for storing your data and files, as well as a web-based code editor for editing files and running scripts.++This means that you can clone a github repo, run a couple of Terraform commands, and have a Remotion-ready GCP project in minutes π.++1. In the top right hand corner of the screen, click the Activate Cloud Shell icon++ <img src="/img/gcp/selectCloudShell.jpg" width="200" />++2. Within the Cloud Shell, type+ ```bash+ git clone https://github.com/UmungoBungo/remotion-gcp-terraform.git remotion-gcp-terraform/+ ```++<!-- ToDo - host this in the official Remotion repo -->++3. Change directory into the new folder+ ```bash+ cd remotion-gcp-terraform/+ ```+4. Within the terraform file, there is a variable named project_id. This needs to be set to your newly created Remotion project. Because Cloud Shell is already authenticated with GCP, the variable can be set using the following command:+ ```bash+ export TF_VAR_project_id=$(gcloud config get-value project)+ ```+5. As Terraform is natively available in Cloud Shell, these commands can be executed without further installation.+ Run the following commands sequentially;+ ```bash+ terraform init+ ```+ :::info+ Terraform will download any required provider plugins and modules and create a .terraform directory in your working directory.+ :::+ ```bash+ terraform plan+ ```+ :::info+ Terraform checks the code to see what resources need to created, updated or deleted, and then displays what it will do without actually making any changes.+ :::+ Check the output for changes about to be made to the project.+ ```bash+ terraform apply+ ```+ :::info+ Terraform deploys the resources as defined in the .tf files.+ :::+6. When the apply is complete, it will output a script to run in the command line. Running this will create a key for the service account and store it on the virtual machine. The command should look similar to the following;+ ```bash+ gcloud iam service-accounts keys create key.json --iam-account=remotion-sa@<project_name>.iam.gserviceaccount.com+ ```+ :::warning+ These keys need to remain secret, and will be deleted off the virtual machine in a future step.+ :::+7. The key file has been generated on the virtual machine. The follow command will build the .env file that is needed at the root of the Remotion project in order to interact with GCP;+ ```bash+ echo "REMOTION_GCP_PRIVATE_KEY=$(jq '.private_key' key.json)" >> .env && \+ echo "REMOTION_GCP_CLIENT_EMAIL=$(jq '.client_email' key.json)" >> .env && \+ echo "REMOTION_GCP_PROJECT_ID=$(gcloud config get-value project)" >> .env+ ```+8. Download the .env file by clicking the vertical ellipsis, in the top right of the cloud shell window, and selecting Download. Then type .env at the end of the prefilled path, and click DOWNLOAD;+ <img src="/img/gcp/downloadEnv.jpg" width="350" />+ <br />+ <br />+ <img src="/img/gcp/downloadEnvFolder.png" width="300" />++9. Remove the .env file and key.json from the virtual machine, using this command;++ ```bash+ rm key.json .env+ ```++10. Place the downloaded .env file into the root of the Remotion project. You may need to rename it from `env.txt`, to `.env`. The file should have this format;++ ```txt title=".env"+ REMOTION_GCP_PRIVATE_KEY=<private key>+ REMOTION_GCP_CLIENT_EMAIL=<client email>+ REMOTION_GCP_PROJECT_ID=<project id>+ ```++## 5. Optional: Validate the permission setup++- Run `npx remotion gcp policies validate`++<hr/>++For the following steps, you may execute them on the CLI, or programmatically using the Node.JS APIs.++## 6. Deploy a function++<Tabs+defaultValue="cli"+values={[+{ label: 'CLI', value: 'cli', },+{ label: 'Node.JS', value: 'node', },+]+}>+<TabItem value="cli">++Deploy a function that can render videos into your AWS account by executing the following command:++```bash+npx remotion lambda functions deploy+```++</TabItem>+<TabItem value="node">++You can deploy a function that can render videos into your AWS account using [`deployFunction()`](/docs/lambda/deployfunction).++```ts twoslash+// @module: ESNext+// @target: ESNext+import { deployFunction } from "@remotion/lambda";++// ---cut---+const { functionName } = await deployFunction({+ region: "us-east-1",+ timeoutInSeconds: 120,+ memorySizeInMb: 2048,+ createCloudWatchLogGroup: true,+ architecture: "arm64",+});+```++The function name is returned which you'll need for rendering.+</TabItem>+</Tabs>++The function consists of necessary binaries and JavaScript code that can take a [serve URL](/docs/terminology#serve-url) and make renders from it. A function is bound to the Remotion version, if you upgrade Remotion, you [need to deploy a new function](/docs/lambda/upgrading). A function does not include your Remotion code, it will be deployed in the next step instead.++## 9. Deploy a site++<Tabs+defaultValue="cli"+values={[+{ label: 'CLI', value: 'cli', },+{ label: 'Node.JS', value: 'node', },+]+}>+<TabItem value="cli">++Run the following command to deploy your Remotion project to an S3 bucket. Pass as the last argument the [entry point](/docs/terminology#entry-point) of the project.++```bash+npx remotion lambda sites create src/index.ts --site-name=my-video+```++A [`serveUrl`](/docs/terminology#serve-url) will be printed pointing to the deployed project.++When you update your Remotion video in the future, redeploy your site. Pass the same [`--site-name`](/docs/lambda/cli/sites#--site-name) to overwrite the previous deploy. If you don't pass [`--site-name`](/docs/lambda/cli/sites#--site-name), a unique URL will be generated on every deploy.++</TabItem>+<TabItem value="node">++First, you need to create an S3 bucket in your preferred region. If one already exists, it will be used instead:++```ts twoslash+// @module: ESNext+// @target: ESNext+import path from "path";+import { deploySite, getOrCreateBucket } from "@remotion/lambda";++const { bucketName } = await getOrCreateBucket({+ region: "us-east-1",+});+```++Next, upload your Remotion project to an S3 bucket. Specify the entry point of your Remotion project, this is the file where [`registerRoot()`](/docs/register-root) is called.++```ts twoslash+// @module: ESNext+// @target: ESNext+import path from "path";+import { deploySite, getOrCreateBucket } from "@remotion/lambda";++const { bucketName } = await getOrCreateBucket({+ region: "us-east-1",+});+// ---cut---+const { serveUrl } = await deploySite({+ bucketName,+ entryPoint: path.resolve(process.cwd(), "src/index.ts"),+ region: "us-east-1",+ siteName: "my-video",+});+```++When you update your Remotion video in the future, redeploy your site. Pass the same [`siteName`](/docs/lambda/deploysite#sitename) to overwrite the previous deploy. If you don't pass [`siteName`](/docs/lambda/deploysite#sitename), a unique URL will be generated on every deploy.++</TabItem>+</Tabs>++## 10. Check AWS concurrency limit++Check the concurrency limit that AWS has given to your account:++```+npx remotion lambda quotas+```++By default, it is `1000` concurrent invocations per region. However, new accounts might have a limit [as low as `10`](/docs/lambda/troubleshooting/rate-limit). Each Remotion render may use as much as 200 functions per render concurrently, so if your assigned limit is very low, [you might want to request an increase right away](/docs/lambda/troubleshooting/rate-limit).++## 11. Render a video++<Tabs+defaultValue="cli"+values={[+{ label: 'CLI', value: 'cli', },+{ label: 'Node.JS', value: 'node', },+]+}>+<TabItem value="cli">++Take the URL you received from the step 8 - your "serve URL" - and run the following command. Also pass in the [ID of the composition](/docs/composition) you'd like to render.++```bash+npx remotion lambda render <serve-url> <composition-id>+```++Progress will be printed until the video finished rendering. Congrats! You rendered your first video using Remotion Lambda π++</TabItem>+<TabItem value="node">++You already have the function name from a previous step. But since you only need to deploy a function once, it's useful to retrieve the name of your deployed function programmatically before rendering a video in case your Node.JS program restarts. We can call [`getFunctions()`](/docs/lambda/getfunctions) with the `compatibleOnly` flag to get only functions with a matching version.++```ts twoslash+// @module: ESNext+// @target: ESNext+import {+ getFunctions,+ renderMediaOnLambda,+ getRenderProgress,+} from "@remotion/lambda";++const functions = await getFunctions({+ region: "us-east-1",+ compatibleOnly: true,+});++const functionName = functions[0].functionName;+```++We can now trigger a render using the [`renderMediaOnLambda()`](/docs/lambda/rendermediaonlambda) function.++```ts twoslash+// @module: ESNext+// @target: ESNext+import {+ getFunctions,+ renderMediaOnLambda,+ getRenderProgress,+} from "@remotion/lambda";++const url = "string";+const functions = await getFunctions({+ region: "us-east-1",+ compatibleOnly: true,+});++const functionName = functions[0].functionName;+// ---cut---++const { renderId, bucketName } = await renderMediaOnLambda({+ region: "us-east-1",+ functionName,+ serveUrl: url,+ composition: "HelloWorld",+ inputProps: {},+ codec: "h264",+ imageFormat: "jpeg",+ maxRetries: 1,+ framesPerLambda: 20,+ privacy: "public",+});+```++The render will now run and after a while the video will be available in your S3 bucket. You can at any time get the status of the video render by calling [`getRenderProgress()`](/docs/lambda/getrenderprogress).++```ts twoslash+// @module: ESNext+// @target: ESNext+import {+ getFunctions,+ renderMediaOnLambda,+ getRenderProgress,+} from "@remotion/lambda";++const url = "string";+const functions = await getFunctions({+ region: "us-east-1",+ compatibleOnly: true,+});++const functionName = functions[0].functionName;++const { renderId, bucketName } = await renderMediaOnLambda({+ region: "us-east-1",+ functionName,+ serveUrl: url,+ composition: "HelloWorld",+ inputProps: {},+ codec: "h264",+ imageFormat: "jpeg",+ maxRetries: 1,+ framesPerLambda: 20,+ privacy: "public",+});+// ---cut---+while (true) {+ await new Promise((resolve) => setTimeout(resolve, 1000));+ const progress = await getRenderProgress({+ renderId,+ bucketName,+ functionName,+ region: "us-east-1",+ });+ if (progress.done) {+ console.log("Render finished!", progress.outputFile);+ process.exit(0);+ }+ if (progress.fatalErrorEncountered) {+ console.error("Error enountered", progress.errors);+ process.exit(1);+ }+}+```++This code will poll every second to check the progress of the video and exit the script if the render is done. Congrats! [Check your S3 Bucket](https://s3.console.aws.amazon.com/s3/) - you just rendered your first video using Remotion Lambda π++</TabItem>+</Tabs>++## Next steps++- Select [which region(s)](/docs/lambda/region-selection) you want to run Remotion Lambda in.+- Familiarize yourself with the CLI and the Node.JS APIs (list in sidebar).+- Learn how to [upgrade Remotion Lambda](/docs/lambda/upgrading).+- Before going live, go through the [Production checklist](/docs/lambda/checklist).+- If you have any questions, go through the [FAQ](/docs/lambda/faq) or ask in our [Discord channel](https://remotion.dev/discord)diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.jsindex b18e003b6e..89b5a8597d 100644--- a/packages/docs/sidebars.js+++ b/packages/docs/sidebars.js@@ -32,6 +32,24 @@ module.exports = {"lambda/cli/quotas",],},+ {+ type: "category",+ label: "gcp",+ link: {+ type: "doc",+ id: "gcp/cli",+ },+ items: [+ "lambda/cli/sites",+ "lambda/cli/functions",+ "lambda/cli/render",+ "lambda/cli/still",+ "lambda/cli/policies",+ "lambda/cli/compositions",+ "lambda/cli/regions",+ "lambda/cli/quotas",+ ],+ },"cli/benchmark","cli/install","cli/versions",@@ -462,7 +480,7 @@ module.exports = {id: "gcp",},items: [- "lambda/setup",+ "gcp/setup","gcp/region-selection"],},diff --git a/packages/docs/static/img/gcp/createSA.png b/packages/docs/static/img/gcp/createSA.pngnew file mode 100644index 0000000000..95b2f14008Binary files /dev/null and b/packages/docs/static/img/gcp/createSA.png differdiff --git a/packages/docs/static/img/gcp/downloadEnv.jpg b/packages/docs/static/img/gcp/downloadEnv.jpgnew file mode 100644index 0000000000..8edb03b045Binary files /dev/null and b/packages/docs/static/img/gcp/downloadEnv.jpg differdiff --git a/packages/docs/static/img/gcp/downloadEnvFolder.png b/packages/docs/static/img/gcp/downloadEnvFolder.pngnew file mode 100644index 0000000000..7297e97e96Binary files /dev/null and b/packages/docs/static/img/gcp/downloadEnvFolder.png differdiff --git a/packages/docs/static/img/gcp/saRole.png b/packages/docs/static/img/gcp/saRole.pngnew file mode 100644index 0000000000..f0f7d2775dBinary files /dev/null and b/packages/docs/static/img/gcp/saRole.png differdiff --git a/packages/docs/static/img/gcp/selectCloudShell.jpg b/packages/docs/static/img/gcp/selectCloudShell.jpgnew file mode 100644index 0000000000..f6beabfb9fBinary files /dev/null and b/packages/docs/static/img/gcp/selectCloudShell.jpg differdiff --git a/packages/gcp/src/api/helpers/get-auth-client-for-url.ts b/packages/gcp/src/api/helpers/get-auth-client-for-url.tsnew file mode 100644index 0000000000..4ef0577e58--- /dev/null+++ b/packages/gcp/src/api/helpers/get-auth-client-for-url.ts@@ -0,0 +1,12 @@+import {GoogleAuth} from 'google-auth-library';++export const getAuthClientForUrl = async (url: string) => {+ const auth = new GoogleAuth({+ credentials: {+ client_email: process.env.REMOTION_GCP_CLIENT_EMAIL,+ private_key: process.env.REMOTION_GCP_PRIVATE_KEY,+ },+ });+ const client = await auth.getIdTokenClient(url);+ return client;+};diff --git a/packages/gcp/src/api/iam-validation/simulate.ts b/packages/gcp/src/api/iam-validation/simulate.tsnew file mode 100644index 0000000000..4bb47203c6--- /dev/null+++ b/packages/gcp/src/api/iam-validation/simulate.ts@@ -0,0 +1,69 @@+import {GoogleAuth} from 'google-auth-library';+import saPermissions from '../../shared/sa-permissions.json';++export const logPermissionOutput = (output: SimulationResult) => {+ return [output.decision ? 'β ' : 'β', output.permissionName].join(' ');+};++type SimulationResult = {+ decision: true | false;+ permissionName: string;+};++type SimulatePermissionsInput = {+ onSimulation?: (result: SimulationResult) => void;+};++type SimulatePermissionsOutput = {+ results: SimulationResult[];+};++/**+ * @description Simulates calls using the AWS Simulator to validate the correct permissions.+ * @see [Remotion-Documentation](http://remotion.dev/docs/gcp/simulatepermissions)+ * @see [GCP-Documentation]https://cloud.google.com/iam/docs/testing-permissions)+ * @param {(result: SimulationResult) => void} options.onSimulation Function to run on each simulation result+ * @returns {Promise<SimulatePermissionsOutput>} See documentation for detailed response structure.+ */+export const simulatePermissions = async (+ options: SimulatePermissionsInput+): Promise<SimulatePermissionsOutput> => {+ const auth = new GoogleAuth({+ credentials: {+ client_email: process.env.REMOTION_GCP_CLIENT_EMAIL,+ private_key: process.env.REMOTION_GCP_PRIVATE_KEY,+ },+ scopes: 'https://www.googleapis.com/auth/cloud-platform',+ });+ const client = await auth.getClient();++ const data = {+ permissions: saPermissions.list,+ };++ const results: SimulationResult[] = [];++ const response: {+ data: {+ permissions: string[];+ };+ } = await client.request({+ url: `https://cloudresourcemanager.googleapis.com/v1/projects/${process.env.REMOTION_GCP_PROJECT_ID}:testIamPermissions`,+ method: 'POST',+ data,+ });++ saPermissions.list.forEach((permission) => {+ if (response?.data?.permissions.includes(permission)) {+ const thisResult = {decision: true, permissionName: permission};+ results.push(thisResult);+ options.onSimulation?.(thisResult);+ } else {+ const thisResult = {decision: false, permissionName: permission};+ results.push(thisResult);+ options.onSimulation?.(thisResult);+ }+ });++ return {results};+};diff --git a/packages/gcp/src/api/render-media-on-gcp.ts b/packages/gcp/src/api/render-media-on-gcp.tsindex 0ea06067cd..c9bf9c5690 100644--- a/packages/gcp/src/api/render-media-on-gcp.ts+++ b/packages/gcp/src/api/render-media-on-gcp.ts@@ -1,9 +1,9 @@-import {GoogleAuth} from 'google-auth-library';import got from 'got/dist/source';import {validateCloudRunUrl} from '../shared/validate-cloudrun-url';import type {GcpCodec} from '../shared/validate-gcp-codec';import {validateGcpCodec} from '../shared/validate-gcp-codec';import {validateServeUrl} from '../shared/validate-serveurl';+import {getAuthClientForUrl} from './helpers/get-auth-client-for-url';import {parseCloudRunUrl} from './helpers/parse-cloud-run-url';export type RenderMediaOnGcpInput = {@@ -84,14 +84,7 @@ export const renderMediaOnGcp = async ({};if (authenticatedRequest) {- console.log('authenticated request');- const auth = new GoogleAuth({- credentials: {- client_email: process.env.REMOTION_GCP_CLIENT_EMAIL,- private_key: process.env.REMOTION_GCP_PRIVATE_KEY,- },- });- const client = await auth.getIdTokenClient(cloudRunUrl);+ const client = await getAuthClientForUrl(cloudRunUrl);const dataPromise = new Promise((resolve, reject) => {let response = {};diff --git a/packages/gcp/src/api/render-still-on-gcp.ts b/packages/gcp/src/api/render-still-on-gcp.tsindex ecee679a32..165a47c453 100644--- a/packages/gcp/src/api/render-still-on-gcp.ts+++ b/packages/gcp/src/api/render-still-on-gcp.ts@@ -1,7 +1,7 @@-import {GoogleAuth} from 'google-auth-library';import got from 'got';import {validateCloudRunUrl} from '../shared/validate-cloudrun-url';import {validateServeUrl} from '../shared/validate-serveurl';+import {getAuthClientForUrl} from './helpers/get-auth-client-for-url';import {parseCloudRunUrl} from './helpers/parse-cloud-run-url';export type RenderStillOnGcpInput = {@@ -76,13 +76,7 @@ export const renderStillOnGcp = async ({};if (authenticatedRequest) {- const auth = new GoogleAuth({- credentials: {- client_email: process.env.REMOTION_GCP_CLIENT_EMAIL,- private_key: process.env.REMOTION_GCP_PRIVATE_KEY,- },- });- const client = await auth.getIdTokenClient(cloudRunUrl);+ const client = await getAuthClientForUrl(cloudRunUrl);try {const response = await client.request({diff --git a/packages/gcp/src/cli/commands/policies/index.ts b/packages/gcp/src/cli/commands/policies/index.tsnew file mode 100644index 0000000000..7f365a4fea--- /dev/null+++ b/packages/gcp/src/cli/commands/policies/index.ts@@ -0,0 +1,58 @@+import {CliInternals} from '@remotion/cli';+import {BINARY_NAME} from '../../../shared/constants';+import {quit} from '../../helpers/quit';+import {Log} from '../../log';+// import {roleSubcommand, ROLE_SUBCOMMAND} from './role';+// import {userSubcommand, USER_SUBCOMMAND} from './user';+import {validateSubcommand, VALIDATE_SUBCOMMAND} from './validate';++export const POLICIES_COMMAND = 'policies';++const printPoliciesHelp = () => {+ Log.info(`${BINARY_NAME} ${POLICIES_COMMAND} <subcommand>`);+ Log.info();+ Log.info('Available subcommands:');+ Log.info('');+ // Log.info(`${BINARY_NAME} ${POLICIES_COMMAND} ${USER_SUBCOMMAND}`);+ // Log.info(+ // CliInternals.chalk.gray(+ // 'Print the suggested policy to be applied to the user that is attached to the access token.'+ // )+ // );+ // Log.info();+ // Log.info(`${BINARY_NAME} ${POLICIES_COMMAND} ${ROLE_SUBCOMMAND}`);+ // Log.info(+ // CliInternals.chalk.gray(+ // 'Print the suggested policy to be applied to the role that is attached to the lambda function.'+ // )+ // );+ // Log.info();+ Log.info(`${BINARY_NAME} ${POLICIES_COMMAND} ${VALIDATE_SUBCOMMAND}`);+ Log.info(+ CliInternals.chalk.gray(+ 'Validate the current policies setup is correct by running tests using the AWS policy simulator.'+ )+ );+};++export const policiesCommand = (args: string[]) => {+ // if (args[0] === USER_SUBCOMMAND) {+ // return userSubcommand();+ // }++ // if (args[0] === ROLE_SUBCOMMAND) {+ // return roleSubcommand();+ // }++ if (args[0] === VALIDATE_SUBCOMMAND) {+ return validateSubcommand();+ }++ if (args[0]) {+ Log.error(`Subcommand ${args[0]} not found.`);+ printPoliciesHelp();+ quit(1);+ }++ printPoliciesHelp();+};diff --git a/packages/gcp/src/cli/commands/policies/role.ts b/packages/gcp/src/cli/commands/policies/role.tsnew file mode 100644index 0000000000..ecb1a29071--- /dev/null+++ b/packages/gcp/src/cli/commands/policies/role.ts@@ -0,0 +1,7 @@+import {getRolePolicy} from '../../../api/iam-validation/suggested-policy';+import {Log} from '../../log';+export const ROLE_SUBCOMMAND = 'role';++export const roleSubcommand = () => {+ Log.info(getRolePolicy());+};diff --git a/packages/gcp/src/cli/commands/policies/user.ts b/packages/gcp/src/cli/commands/policies/user.tsnew file mode 100644index 0000000000..0e7480b1fc--- /dev/null+++ b/packages/gcp/src/cli/commands/policies/user.ts@@ -0,0 +1,8 @@+import {getUserPolicy} from '../../../api/iam-validation/suggested-policy';+import {Log} from '../../log';++export const USER_SUBCOMMAND = 'user';++export const userSubcommand = () => {+ Log.info(getUserPolicy());+};diff --git a/packages/gcp/src/cli/commands/policies/validate.ts b/packages/gcp/src/cli/commands/policies/validate.tsnew file mode 100644index 0000000000..89b18c3363--- /dev/null+++ b/packages/gcp/src/cli/commands/policies/validate.ts@@ -0,0 +1,27 @@+import {CliInternals} from '@remotion/cli';+import {+ logPermissionOutput,+ simulatePermissions,+} from '../../../api/iam-validation/simulate';+import {Log} from '../../log';++export const VALIDATE_SUBCOMMAND = 'validate';++export const validateSubcommand = async () => {+ try {+ Log.info(+ CliInternals.chalk.blueBright(+ `Checking permissions for ${process.env.REMOTION_GCP_CLIENT_EMAIL}`+ )+ );+ Log.info();+ await simulatePermissions({+ onSimulation: (res) => {+ Log.info(logPermissionOutput(res));+ },+ });+ } catch (err) {+ Log.error('Did not have the required permissions on GCP:');+ Log.error(err);+ }+};diff --git a/packages/gcp/src/cli/index.ts b/packages/gcp/src/cli/index.tsindex bd3c62804e..c8bda43f5d 100644--- a/packages/gcp/src/cli/index.ts+++ b/packages/gcp/src/cli/index.ts@@ -4,6 +4,7 @@ import {compositionsCommand,COMPOSITIONS_COMMAND,} from './commands/compositions';+import {policiesCommand, POLICIES_COMMAND} from './commands/policies';import {regionsCommand, REGIONS_COMMAND} from './commands/regions';import {renderCommand, RENDER_COMMAND} from './commands/render';import {sitesCommand, SITES_COMMAND} from './commands/sites';@@ -37,6 +38,10 @@ const matchCommand = (args: string[], remotionRoot: string) => {return regionsCommand();}+ if (args[0] === POLICIES_COMMAND) {+ return policiesCommand(args.slice(1));+ }+if (args[0] === 'deploy') {Log.info(`The "deploy" command does not exist.`);Log.info(`Did you mean "cloud-run deploy"?`);diff --git a/packages/gcp/src/shared/sa-permissions.json b/packages/gcp/src/shared/sa-permissions.jsonnew file mode 100644index 0000000000..a72c6db3a6--- /dev/null+++ b/packages/gcp/src/shared/sa-permissions.json@@ -0,0 +1,18 @@+{+ "list": [+ "iam.serviceAccounts.actAs",+ "run.operations.get",+ "run.routes.invoke",+ "run.services.create",+ "run.services.list",+ "run.services.update",+ "storage.buckets.create",+ "storage.buckets.get",+ "storage.buckets.list",+ "storage.objects.create",+ "storage.objects.delete",+ "storage.objects.list",+ "run.services.getIamPolicy",+ "run.services.setIamPolicy"+ ]+}\ No newline at end of filediff --git a/packages/gcp/terraform/main.tf b/packages/gcp/terraform/main.tfnew file mode 100644index 0000000000..9024950db7--- /dev/null+++ b/packages/gcp/terraform/main.tf@@ -0,0 +1,64 @@+terraform {+ required_providers {+ google = {+ source = "hashicorp/google"+ version = "4.58.0"+ }+ }++ required_version = ">= 1.4.1"+}++variable "project_id" {+ type = string+ description = "The ID of the project in which the resources will be created."+}+++provider "google" {+ project = var.project_id+ region = "us-central1"+ zone = "us-central1-c"+}++locals {+ permissions = jsondecode(file("${path.module}/../shared/permissions.json"))+}++# Create an IAM role+resource "google_project_iam_custom_role" "remotion_sa" {+ role_id = "RemotionSA"+ title = "Remotion API Service Account"+ description = "Allow the service account to manage necessary resources for Remotion Cloud Run rendering."+ permissions = local.permissions.list+}++# Create a service account+resource "google_service_account" "remotion_sa" {+ account_id = "remotion-sa"+ display_name = "Remotion Service Account"+}++# Bind the IAM role to the service account+resource "google_project_iam_member" "remotion_sa" {+ project = var.project_id+ role = google_project_iam_custom_role.remotion_sa.id+ member = "serviceAccount:${google_service_account.remotion_sa.email}"+}++# Enable Cloud Run API+resource "google_project_service" "cloud_run" {+ project = var.project_id+ service = "run.googleapis.com"+}++# Enable Cloud Resource Manager+resource "google_project_service" "cloud_resource_manager" {+ project = var.project_id+ service = "cloudresourcemanager.googleapis.com"+}++# Output the command to generate service account keys+output "service_account_key_generation_command" {+ value = "gcloud iam service-accounts keys create key.json --iam-account=${google_service_account.remotion_sa.email}"+}diff --git a/packages/gcp/terraform/readme.md b/packages/gcp/terraform/readme.mdnew file mode 100644index 0000000000..528d69386b--- /dev/null+++ b/packages/gcp/terraform/readme.md@@ -0,0 +1,41 @@+#### Cloudshell tutorial++https://github.com/hashicorp/terraform-getting-started-gcp-cloud-shell/blob/master/tutorial/cloudshell_tutorial.md++## Permission explanations for APIs++- run.googleapis.com+ Cloud Run API+- cloudresourcemanager.googleapis.com+ Cloud Resource Manager API++## Permission explanations for Service Account role++- iam.serviceAccounts.actAs+ - When deploying, act as the default service account, which will grant further permissions required during deployment.+- run.operations.get+ - Required during deployment to confirm that deployment was successful.+- run.routes.invoke+ - Call the deployed Cloud Run services, in order to perform a render.+- run.services.create+ - Deploy new, and edit existing, Cloud Run services+- run.services.list+ - Get a list of existing Cloud Run services, to ensure no unintended overwriting.+- run.services.update+ - Update a Cloud Run service, for instance providing it with more Memory or CPU.+- storage.buckets.create+ - Create the storage bucket to store the bundled site, plus render output+- storage.buckets.get+ - ToDo...+- storage.buckets.list+ - Get a list of existing Cloud Storage resources, to ensure no unintended overwriting of storage buckets.+- storage.objects.create+ - Create new objects in storage. This could be bundled sites, or renders, or logs.+- storage.objects.delete+ - ToDo...+- storage.objects.list+ - ToDo...+- run.services.getIamPolicy+ - used to check the existing IAM policy on a service, before modifying it for (un)authenticated invoking.+- run.services.setIamPolicy+ - used to set the IAM policy on a service, to allow unauthenticated invoking, or remove unauthenticated invoking.diff --git a/packages/gcp/tsconfig.json b/packages/gcp/tsconfig.jsonindex 40d917d007..7584080359 100644--- a/packages/gcp/tsconfig.json+++ b/packages/gcp/tsconfig.json@@ -4,7 +4,8 @@"module": "commonjs","esModuleInterop": true,"strict": true,- "outDir": "dist"+ "outDir": "dist",+ "resolveJsonModule": true,},"include": ["src/**/*",