π₯ Make videos programmatically with React
can now make authenticated calls to cloudRun, using service account
Matt McGillivrayb132cd2d9070
diff --git a/packages/gcp/package.json b/packages/gcp/package.jsonindex e3e26fc50f..9270c15c22 100644--- a/packages/gcp/package.json+++ b/packages/gcp/package.json@@ -17,6 +17,7 @@"@google-cloud/functions-framework": "^3.1.3","@google-cloud/storage": "^6.9.1","@google-cloud/run": "^0.4.0",+ "google-auth-library": "^8.7.0","@remotion/bundler": "workspace:*","@remotion/cli": "workspace:*","@remotion/renderer": "workspace:*",@@ -34,4 +35,4 @@"@jonny/eslint-config": "3.0.266","vitest": "0.24.3"}-}+}\ No newline at end of filediff --git a/packages/gcp/src/api/cloud-run-allow-unauthenticated-access.ts b/packages/gcp/src/api/cloud-run-allow-unauthenticated-access.tsindex f7aa1f449d..ea8fcdc3e6 100644--- a/packages/gcp/src/api/cloud-run-allow-unauthenticated-access.ts+++ b/packages/gcp/src/api/cloud-run-allow-unauthenticated-access.ts@@ -7,20 +7,88 @@ import {getCloudRunClient} from './helpers/get-cloud-run-client';* @returns {Promise<Boolean>} True if operation was successful. False if not.*/export const allowUnauthenticatedAccess = async (- serviceName: string+ serviceName: string,+ allow: boolean): Promise<Boolean> => {const cloudRunClient = getCloudRunClient();- await cloudRunClient.setIamPolicy({++ // ToDo: once this is finalised, need to test out the testCall code - is it able to invoke the Cloud Run service using the stored json credentials, where as the got() call should fail.++ const existingPolicy = await cloudRunClient.getIamPolicy({resource: serviceName,- policy: {- bindings: [- {- role: 'roles/run.invoker',- members: ['allUsers'],- },- ],- },});+ const existingBindings = existingPolicy[0].bindings || [];++ const invokerBindings = existingPolicy[0].bindings?.filter(+ (binding) => binding.role === 'roles/run.invoker'+ );+ if (allow) {+ /* allow allUsers to invoke cloud run */++ let finalMembers: string[] = [];++ if (invokerBindings?.[0]) {+ if (invokerBindings?.[0].members?.indexOf('allUsers') === -1) {+ // allUsers not present for roles/run.invoker+ finalMembers = invokerBindings[0].members.concat(['allUsers']);+ } else {+ // allUsers already present for roles/run.invoker+ return true;+ }+ } else {+ // no existing bindings found for roles/run.invoker+ finalMembers = ['allUsers'];+ }++ await cloudRunClient.setIamPolicy({+ resource: serviceName,+ policy: {+ bindings: [+ ...existingBindings,+ {+ role: 'roles/run.invoker',+ members: finalMembers,+ },+ ],+ },+ });+ } else {+ /* Ensure allUsers is not on permitted to invoke cloud run */++ if (!existingBindings.length) {+ // there are no bindings on this service+ return true;+ }++ if (invokerBindings?.[0]) {+ if (invokerBindings[0].members?.indexOf('allUsers') === -1) {+ // allUsers not present for roles/run.invoker+ return true;+ }++ invokerBindings[0].members?.splice(+ invokerBindings[0].members.indexOf('allUsers'),+ 1+ );+ } else {+ // no existing bindings found for roles/run.invoker+ return true;+ }++ await cloudRunClient.setIamPolicy({+ resource: serviceName,+ policy: {+ bindings: [+ ...existingBindings,+ {+ role: 'roles/run.invoker',+ members: invokerBindings[0].members,+ },+ ],+ },+ });+ }+return true;};diff --git a/packages/gcp/src/api/render-media-on-gcp.ts b/packages/gcp/src/api/render-media-on-gcp.tsindex f717dcde7a..0ea06067cd 100644--- a/packages/gcp/src/api/render-media-on-gcp.ts+++ b/packages/gcp/src/api/render-media-on-gcp.ts@@ -1,4 +1,5 @@-import got from 'got';+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';@@ -6,6 +7,7 @@ import {validateServeUrl} from '../shared/validate-serveurl';import {parseCloudRunUrl} from './helpers/parse-cloud-run-url';export type RenderMediaOnGcpInput = {+ authenticatedRequest: boolean;cloudRunUrl: string;// serviceName?: string;serveUrl: string;@@ -18,6 +20,7 @@ export type RenderMediaOnGcpInput = {};export type RenderMediaOnGcpOutput = {+ authenticatedRequest: boolean;publicUrl: string;cloudStorageUri: string;size: string;@@ -37,6 +40,7 @@ export type RenderMediaOnGcpErrOutput = {/*** @description Triggers a render on a GCP Cloud Run service given a composition and a Cloud Run URL.* @see [Documentation](https://remotion.dev/docs/lambda/renderMediaOnGcp)+ * @param params.authenticatedRequest If this is an authenticated request, .env file will be checked for GCP credentials* @param params.cloudRunUrl The url of the Cloud Run service that should be used* @param params.serviceName The name of the Cloud Run service that should be used* @param params.serveUrl The URL of the deployed project@@ -50,6 +54,7 @@ export type RenderMediaOnGcpErrOutput = {*/export const renderMediaOnGcp = async ({+ authenticatedRequest,cloudRunUrl,// serviceName,serveUrl,@@ -68,7 +73,7 @@ export const renderMediaOnGcp = async ({// todo: allow serviceName to be passed in, and fetch the cloud run URL based on the name- const postData = {+ const data = {type: 'media',composition,serveUrl,@@ -78,35 +83,89 @@ export const renderMediaOnGcp = async ({outputFile,};- const dataPromise = new Promise((resolve, reject) => {- let response = {};- got.stream- .post(cloudRunUrl, {json: postData})- .on('data', (chunk) => {- const chunkResponse = JSON.parse(chunk.toString());- if (chunkResponse.response) {- response = chunkResponse.response;- } else if (chunkResponse.onProgress) {- updateRenderProgress?.(chunkResponse.onProgress);- }- })- .on('end', () => {- resolve(response);- })- .on('error', (error) => {- reject(error);- });- });+ 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);- try {- const response = await dataPromise;- return response;- } catch (e) {- return {- // TODO: How do we get the project ID?- message: `Cloud Run Service failed. View logs at https://console.cloud.google.com/run/detail/${cloudRunInfo.region}/${cloudRunInfo.serviceName}/logs?project={PROJECT_ID}`,- error: e,- status: 'error',- };+ const dataPromise = new Promise((resolve, reject) => {+ let response = {};+ client+ .request({+ url: cloudRunUrl,+ method: 'POST',+ data,+ responseType: 'stream',+ })+ .then((postResponse) => {+ const stream: any = postResponse.data;++ stream.on('data', (chunk: Buffer) => {+ const chunkResponse = JSON.parse(chunk.toString());+ if (chunkResponse.response) {+ response = chunkResponse.response;+ } else if (chunkResponse.onProgress) {+ updateRenderProgress?.(chunkResponse.onProgress);+ }+ });++ stream.on('end', () => {+ resolve(response);+ });++ stream.on('error', (error: any) => {+ reject(error);+ });+ });+ });++ try {+ const response = await dataPromise;+ return response;+ } catch (e) {+ return {+ // TODO: How do we get the project ID?+ message: `Cloud Run Service failed. View logs at https://console.cloud.google.com/run/detail/${cloudRunInfo.region}/${cloudRunInfo.serviceName}/logs?project={PROJECT_ID}`,+ error: e,+ status: 'error',+ };+ }+ } else {+ const dataPromise = new Promise((resolve, reject) => {+ let response = {};+ got.stream+ .post(cloudRunUrl, {json: data})+ .on('data', (chunk) => {+ const chunkResponse = JSON.parse(chunk.toString());+ if (chunkResponse.response) {+ response = chunkResponse.response;+ } else if (chunkResponse.onProgress) {+ updateRenderProgress?.(chunkResponse.onProgress);+ }+ })+ .on('end', () => {+ resolve(response);+ })+ .on('error', (error) => {+ reject(error);+ });+ });++ try {+ const response = await dataPromise;+ return response;+ } catch (e) {+ return {+ // TODO: How do we get the project ID?+ message: `Cloud Run Service failed. View logs at https://console.cloud.google.com/run/detail/${cloudRunInfo.region}/${cloudRunInfo.serviceName}/logs?project={PROJECT_ID}`,+ error: e,+ status: 'error',+ };+ }}};diff --git a/packages/gcp/src/api/render-still-on-gcp.ts b/packages/gcp/src/api/render-still-on-gcp.tsindex f2a32f5b04..ecee679a32 100644--- a/packages/gcp/src/api/render-still-on-gcp.ts+++ b/packages/gcp/src/api/render-still-on-gcp.ts@@ -1,9 +1,11 @@+import {GoogleAuth} from 'google-auth-library';import got from 'got';import {validateCloudRunUrl} from '../shared/validate-cloudrun-url';import {validateServeUrl} from '../shared/validate-serveurl';-import { parseCloudRunUrl } from './helpers/parse-cloud-run-url';+import {parseCloudRunUrl} from './helpers/parse-cloud-run-url';export type RenderStillOnGcpInput = {+ authenticatedRequest: boolean;cloudRunUrl: string;// serviceName?: string;serveUrl: string;@@ -33,6 +35,7 @@ export type RenderStillOnGcpErrOutput = {/*** @description Triggers a render on a GCP Cloud Run service given a composition and a Cloud Run URL.* @see [Documentation](https://remotion.dev/docs/lambda/renderStillOnGcp)+ * @param params.authenticatedRequest If this is an authenticated request, .env file will be checked for GCP credentials* @param params.cloudRunUrl The url of the Cloud Run service that should be used* @param params.serviceName The name of the Cloud Run service that should be used* @param params.serveUrl The URL of the deployed project@@ -45,6 +48,7 @@ export type RenderStillOnGcpErrOutput = {*/export const renderStillOnGcp = async ({+ authenticatedRequest,cloudRunUrl,// serviceName,serveUrl,@@ -59,10 +63,10 @@ export const renderStillOnGcp = async ({validateCloudRunUrl(cloudRunUrl);const cloudRunInfo = parseCloudRunUrl(cloudRunUrl);-+// todo: allow serviceName to be passed in, and fetch the cloud run URL based on the name- const postData = {+ const data = {type: 'still',composition,serveUrl,@@ -71,17 +75,43 @@ export const renderStillOnGcp = async ({outputFile,};- try {- const response: RenderStillOnGcpOutput = await got- .post(cloudRunUrl, {json: postData})- .json();- return response;- } catch (e) {- return {- // TODO: How do we get the project ID?- message: `Cloud Run Service failed. View logs at https://console.cloud.google.com/run/detail/${cloudRunInfo.region}/${cloudRunInfo.serviceName}/logs?project={PROJECT_ID}`,- error: e,- status: 'error',- };+ 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);++ try {+ const response = await client.request({+ url: cloudRunUrl,+ method: 'POST',+ data,+ });+ return response.data as RenderStillOnGcpOutput;+ } catch (e) {+ return {+ // TODO: How do we get the project ID?+ message: `Cloud Run Service failed. View logs at https://console.cloud.google.com/run/detail/${cloudRunInfo.region}/${cloudRunInfo.serviceName}/logs?project={PROJECT_ID}`,+ error: e,+ status: 'error',+ };+ }+ } else {+ try {+ const response: RenderStillOnGcpOutput = await got+ .post(cloudRunUrl, {json: data})+ .json();+ return response;+ } catch (e) {+ return {+ // TODO: How do we get the project ID?+ message: `Cloud Run Service failed. View logs at https://console.cloud.google.com/run/detail/${cloudRunInfo.region}/${cloudRunInfo.serviceName}/logs?project={PROJECT_ID}`,+ error: e,+ status: 'error',+ };+ }}};diff --git a/packages/gcp/src/api/testCall.ts b/packages/gcp/src/api/testCall.tsnew file mode 100644index 0000000000..70ad01b6f1--- /dev/null+++ b/packages/gcp/src/api/testCall.ts@@ -0,0 +1,51 @@+import {CliInternals} from '@remotion/cli';+import fs from 'fs';+import {GoogleAuth} from 'google-auth-library';++export type TestInput = {+ cloudRunUrl: string;+};++export const testAuth = async ({cloudRunUrl}: TestInput): Promise<any> => {+ const composition = 'still-zoom';+ const outputBucket = 'remotioncloudrun-n8x4pc7dz3';+ const outName = 'out.png';+ const serveUrl =+ 'https://storage.googleapis.com/remotioncloudrun-n8x4pc7dz3/sites/axp52acnh2/index.html';+ const inputProps = {};+ const outputFile = outName;++ CliInternals.Log.info(+ CliInternals.chalk.gray(+ `+Sending request to Cloud Run:++ Cloud Run Service URL = ${cloudRunUrl}+ Type = still+ Composition = ${composition}+ Output Bucket = ${outputBucket}+ Output File = ${outName}+ `.trim()+ )+ );++ const data = {+ type: 'still',+ composition,+ serveUrl,+ inputProps,+ outputBucket,+ outputFile,+ };+ const sa_data = fs.readFileSync('./sa-key.json', 'utf8');+ const credentials = JSON.parse(sa_data);++ const auth = new GoogleAuth({credentials});+ const client = await auth.getIdTokenClient(cloudRunUrl);+ const res = await client.request({+ url: cloudRunUrl,+ method: 'POST',+ data,+ });+ console.info(res.data);+};diff --git a/packages/gcp/src/cli/commands/cloud-run/deploy.ts b/packages/gcp/src/cli/commands/cloud-run/deploy.tsindex 6ec18f1d8f..9462e5e7e4 100644--- a/packages/gcp/src/cli/commands/cloud-run/deploy.ts+++ b/packages/gcp/src/cli/commands/cloud-run/deploy.ts@@ -101,9 +101,10 @@ Validating Deployment of Cloud Run Service:));- if (allowUnauthenticated) {- await allowUnauthenticatedAccessToService(deployRevisionResult.name);- }+ await allowUnauthenticatedAccessToService(+ deployRevisionResult.name,+ allowUnauthenticated+ );} else {Log.info(CliInternals.chalk.gray('deploy cancelled'));quit(1); // TODO: Check with Jonny what to pass to quit - 0 or 1?@@ -147,9 +148,10 @@ Validating Deployment of Cloud Run Service:));- if (allowUnauthenticated) {- await allowUnauthenticatedAccessToService(deployResult.name);- }+ await allowUnauthenticatedAccessToService(+ deployResult.name,+ allowUnauthenticated+ );} catch (e: any) {if (e.code === 6) {Log.error(@@ -168,28 +170,59 @@ Validating Deployment of Cloud Run Service:}};-async function allowUnauthenticatedAccessToService(serviceName: string) {- try {- Log.info(- CliInternals.chalk.white(- '\nAllowing unauthenticated access to the Cloud Run service...'- )- );- await allowUnauthenticatedAccess(serviceName);+async function allowUnauthenticatedAccessToService(+ serviceName: string,+ allowUnauthenticated: boolean+) {+ if (allowUnauthenticated) {+ try {+ Log.info(+ CliInternals.chalk.white(+ '\nAllowing unauthenticated access to the Cloud Run service...'+ )+ );+ await allowUnauthenticatedAccess(serviceName, allowUnauthenticated);- Log.info();+ Log.info();- Log.info(- CliInternals.chalk.blueBright(- ` β Unauthenticated access granted on ${serviceName}`- )- );- } catch (e) {- Log.error(- CliInternals.chalk.red(- ` Failed to allow unauthenticated access to the Cloud Run service.`- )- );- throw e;+ Log.info(+ CliInternals.chalk.blueBright(+ ` β Unauthenticated access granted on ${serviceName}`+ )+ );+ } catch (e) {+ Log.error(+ CliInternals.chalk.red(+ ` Failed to allow unauthenticated access to the Cloud Run service.`+ )+ );+ throw e;+ }+ } else {+ try {+ Log.info();++ Log.info(+ CliInternals.chalk.white(+ 'Ensuring only authenticated access to the Cloud Run service...'+ )+ );+ await allowUnauthenticatedAccess(serviceName, allowUnauthenticated);++ Log.info();++ Log.info(+ CliInternals.chalk.blueBright(+ ` π Only authenticated access granted on ${serviceName}`+ )+ );+ } catch (e) {+ Log.error(+ CliInternals.chalk.red(+ ` Failed to allow unauthenticated access to the Cloud Run service.`+ )+ );+ throw e;+ }}}diff --git a/packages/gcp/src/cli/commands/render/helpers/renderArgsCheck.ts b/packages/gcp/src/cli/commands/render/helpers/renderArgsCheck.tsindex f19990f813..0e7fc5a03e 100644--- a/packages/gcp/src/cli/commands/render/helpers/renderArgsCheck.ts+++ b/packages/gcp/src/cli/commands/render/helpers/renderArgsCheck.ts@@ -81,6 +81,8 @@ export const renderArgsCheck = async (outputBucket = bucketName;}+ const authenticatedRequest = !parsedGcpCli['unauthenticated-request'];+return {serveUrl,cloudRunUrl,@@ -89,5 +91,6 @@ export const renderArgsCheck = async (codec,inputProps,outputBucket,+ authenticatedRequest,};};diff --git a/packages/gcp/src/cli/commands/render/index.ts b/packages/gcp/src/cli/commands/render/index.tsindex e554f02282..092b95f918 100644--- a/packages/gcp/src/cli/commands/render/index.ts+++ b/packages/gcp/src/cli/commands/render/index.ts@@ -4,6 +4,7 @@ import {BINARY_NAME} from '../../../shared/constants';import {quit} from '../../helpers/quit';import {renderMediaSubcommand, RENDER_MEDIA_SUBCOMMAND} from './renderMedia';import {renderStillSubcommand, RENDER_STILL_SUBCOMMAND} from './renderStill';+import {testAuthSubcommand, TEST_AUTH_SUBCOMMAND} from './testAuth';export const RENDER_COMMAND = 'render';@@ -30,6 +31,11 @@ export const renderCommand = (args: string[], remotionRoot: string) => {return renderStillSubcommand(args.slice(1), remotionRoot);}+ if (args[0] === TEST_AUTH_SUBCOMMAND) {+ Log.info(`yo`);+ return testAuthSubcommand(args.slice(1));+ }+if (args[0]) {Log.error(`Subcommand ${args[0]} not found.`);printCloudRunHelp();diff --git a/packages/gcp/src/cli/commands/render/renderMedia.ts b/packages/gcp/src/cli/commands/render/renderMedia.tsindex b2dd848ce8..5e468e775d 100644--- a/packages/gcp/src/cli/commands/render/renderMedia.ts+++ b/packages/gcp/src/cli/commands/render/renderMedia.ts@@ -23,6 +23,7 @@ export const renderMediaSubcommand = async (codec,inputProps,outputBucket,+ authenticatedRequest,} = await renderArgsCheck(RENDER_MEDIA_SUBCOMMAND, args, remotionRoot);// Todo: Check cloudRunUrl is valid, as the error message is obtuse@@ -32,6 +33,7 @@ export const renderMediaSubcommand = async (Sending request to Cloud Run:Cloud Run Service URL = ${cloudRunUrl}+ Authenticated Request = ${authenticatedRequest}Type = mediaComposition = ${composition}Codec = ${codec}@@ -73,6 +75,7 @@ Sending request to Cloud Run:};const res = await renderMediaOnGcp({+ authenticatedRequest,cloudRunUrl,// serviceName,serveUrl,@@ -84,14 +87,14 @@ Sending request to Cloud Run:updateRenderProgress,});- renderProgress.doneIn = Date.now() - renderStart;- updateProgress();-if (res.status === 'error') {const err = res as RenderMediaOnGcpErrOutput;Log.error(CliInternals.chalk.red(err.message));throw err.error;} else {+ renderProgress.doneIn = Date.now() - renderStart;+ updateProgress();+const success = res as RenderMediaOnGcpOutput;Log.info(`diff --git a/packages/gcp/src/cli/commands/render/renderStill.ts b/packages/gcp/src/cli/commands/render/renderStill.tsindex a38bf501ab..b09bee3655 100644--- a/packages/gcp/src/cli/commands/render/renderStill.ts+++ b/packages/gcp/src/cli/commands/render/renderStill.ts@@ -19,9 +19,9 @@ export const renderStillSubcommand = async (cloudRunUrl,composition,outName,- codec,inputProps,outputBucket,+ authenticatedRequest,} = await renderArgsCheck(RENDER_STILL_SUBCOMMAND, args, remotionRoot);// Todo: Check cloudRunUrl is valid, as the error message is obtuse@@ -31,6 +31,7 @@ export const renderStillSubcommand = async (Sending request to Cloud Run:Cloud Run Service URL = ${cloudRunUrl}+ Authenticated Request = ${authenticatedRequest}Type = stillComposition = ${composition}Output Bucket = ${outputBucket}@@ -59,6 +60,7 @@ Sending request to Cloud Run:};const res = await renderStillOnGcp({+ authenticatedRequest,cloudRunUrl,// serviceName,serveUrl,@@ -68,14 +70,14 @@ Sending request to Cloud Run:outputFile: outName,});- doneIn = Date.now() - renderStart;- updateProgress();-if (res.status === 'error') {const err = res as RenderStillOnGcpErrOutput;Log.error(CliInternals.chalk.red(err.message));throw err.error;} else {+ doneIn = Date.now() - renderStart;+ updateProgress();+const success = res as RenderStillOnGcpOutput;Log.info(`diff --git a/packages/gcp/src/cli/commands/render/testAuth.ts b/packages/gcp/src/cli/commands/render/testAuth.tsnew file mode 100644index 0000000000..56404d64d0--- /dev/null+++ b/packages/gcp/src/cli/commands/render/testAuth.ts@@ -0,0 +1,21 @@+import {testAuth} from '../../../api/testCall';+import {quit} from '../../helpers/quit';+import {Log} from '../../log';++export const TEST_AUTH_SUBCOMMAND = 'test';++export const testAuthSubcommand = async (args: string[]) => {+ const cloudRunUrl = args[0];++ if (!cloudRunUrl) {+ Log.error('No Cloud Run Service URL passed.');+ Log.info(+ 'Pass an additional argument specifying the endpoint of your Cloud Run Service.'+ );+ quit(1);+ }++ await testAuth({+ cloudRunUrl,+ });+};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 63fc322cb8..40c6f78433 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -594,6 +594,7 @@ importers:'@remotion/renderer': workspace:*'@types/minimist': 1.2.2eslint: 8.25.0+ google-auth-library: ^8.7.0got: 11.8.2prettier: ^2.7.1prettier-plugin-organize-imports: ^3.2.2@@ -608,6 +609,7 @@ importers:'@remotion/bundler': link:../bundler'@remotion/cli': link:../cli'@remotion/renderer': link:../renderer+ google-auth-library: 8.7.0got: 11.8.2remotion: link:../coredevDependencies: