├── .husky
├── .gitignore
└── pre-commit
├── Procfile
├── .prettierrc
├── doc-gfx
└── architecture.jpg
├── .eslintrc.json
├── .gitignore
├── package.json
├── README.md
├── src
└── index.js
└── LICENSE.md
/.husky/.gitignore:
--------------------------------------------------------------------------------
1 | _
2 |
--------------------------------------------------------------------------------
/Procfile:
--------------------------------------------------------------------------------
1 | web: npm start
2 |
--------------------------------------------------------------------------------
/.husky/pre-commit:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | . "$(dirname "$0")/_/husky.sh"
3 |
4 | npm run precommit
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "trailingComma": "none",
3 | "singleQuote": true,
4 | "tabWidth": 4
5 | }
6 |
--------------------------------------------------------------------------------
/doc-gfx/architecture.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pozil/sf-docs-from-s3/HEAD/doc-gfx/architecture.jpg
--------------------------------------------------------------------------------
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "parserOptions": {
3 | "ecmaVersion": 2021
4 | },
5 | "env": {
6 | "es2021": true,
7 | "node": true
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # This file is used for Git repositories to specify intentionally untracked files that Git should ignore.
2 | # If you are not using git, you can delete this file. For more information see: https://git-scm.com/docs/gitignore
3 | # For useful gitignore templates see: https://github.com/github/gitignore
4 |
5 | .vscode
6 |
7 | # Dependency directories
8 | node_modules/
9 |
10 | # Eslint cache
11 | .eslintcache
12 |
13 | # MacOS system files
14 | .DS_Store
15 |
16 | # Windows system files
17 | Thumbs.db
18 | ehthumbs.db
19 | [Dd]esktop.ini
20 | $RECYCLE.BIN/
21 |
22 | # Local environment variables
23 | .env
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "sf-docs-from-s3",
3 | "version": "1.0.0",
4 | "private": true,
5 | "description": "Proxy that allows to read files from Amazon S3 behind Salesforce OAuth",
6 | "author": "Philippe Ozil (pozil)",
7 | "license": "CC0-1.0",
8 | "main": "src/index.js",
9 | "scripts": {
10 | "start": "node src/index.js",
11 | "lint": "eslint .",
12 | "test": "echo \"Error: no test specified\" && exit 1",
13 | "prettier": "prettier --write \"**/*.{css,html,js,json,md,page,yaml,yml}\"",
14 | "prettier:verify": "prettier --list-different \"**/*.{css,html,js,json,md,page,yaml,yml}\"",
15 | "postinstall": "husky install",
16 | "precommit": "lint-staged"
17 | },
18 | "dependencies": {
19 | "@aws-sdk/client-s3": "^3.95.0",
20 | "@fastify/cookie": "^6.0.0",
21 | "@fastify/session": "^8.2.0",
22 | "dotenv": "^16.0.1",
23 | "fastify": "^3.29.4",
24 | "jsforce": "^1.11.1"
25 | },
26 | "devDependencies": {
27 | "eslint": "^8.16.0",
28 | "husky": "^8.0.1",
29 | "lint-staged": "^13.2.1",
30 | "prettier": "^2.6.2"
31 | },
32 | "lint-staged": {
33 | "**/*.{cls,cmp,component,css,html,js,json,md,page,trigger,xml,yaml,yml}": [
34 | "prettier --write"
35 | ],
36 | "**/*.js": [
37 | "eslint"
38 | ]
39 | },
40 | "volta": {
41 | "node": "16.14.0"
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Download Amazon S3 Documents from Salesforce
2 |
3 | ## About
4 |
5 | This project is a node app that acts as an integration between a Salesforce Org and Amazon S3.
6 |
7 | The project is complementary with this integration that [exports Salesforce documents to Amazon S3](https://github.com/pozil/sf-docs-to-s3).
8 |
9 | The goal of the integration is to allow Salesforce users to download Amazon S3 documents. The integration leverages OAuth 2.0 to authenticate users and performs security checks on document access.
10 |
11 | We download documents from S3 with the following scenario:
12 |
13 | 1. A user clicks on a link on the S3 Document record in Salesforce.
14 | 1. The link redirects the user to the middleware app where the user goes through OAuth authentication using their Salesforce credentials. The OAuth flow is implemented thanks to a Salesforce Connected App.
15 | 1. The middleware run some permission checks and. If the user is allowed to access the document, the middleware uses a S3 API client to retrieve the file from Amazon.
16 | 1. The content of the file is then served back to the user. If the user was already logged in with the connected app before the original request in step 1, the document is sent seamlessly as a response (the user will not notice the intermediate steps).
17 |
18 | 
19 |
20 | ## Installation
21 |
22 | ### Create a Salesforce Connected App
23 |
24 | 1. Log in to your Salesforce org.
25 | 1. At the top right of the page, select the gear icon and then click **Setup**.
26 | 1. From Setup, enter `App Manager` in the Quick Find and select **App Manager**.
27 | 1. Click **New Connected App**.
28 | 1. Enter `Amazon S3 Middleware` as the **Connected App Name**
29 | 1. Enter your **Contact Email**.
30 | 1. Under **API (Enable OAuth Settings)**, check the **Enable OAuth Settings** checkbox.
31 | 1. Enter `https://YOUR_HOST/auth/callback` as the **Callback URL** where `YOUR_HOST` is the host of this node app.
32 | 1. Under **Selected OAuth Scope**, move **Access and manage your data (API)** to the Selected OAuth Scopes list.
33 | 1. Click **Save**.
34 | 1. From this screen, copy the connected app’s **Consumer Key** and **Consumer Secret** some place temporarily.
35 |
36 | ### Deploy and Configure the Node App
37 |
38 | 1. Declare the following environment variables:
39 |
40 | | Variable Name | Description | Example |
41 | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
42 | | `SF_LOGIN_URL` | Salesforce login URL. Either:
- `https://login.salesforce.com` for production and Developer Edition orgs
- `https://login.salesforce.com` for sandboxes and scratch orgs
- your own custom domain. | `https://login.salesforce.com` |
43 | | `SF_AUTH_CALLBACK_URL` | Connected app callback URL where `YOUR_HOST` in the example is the host that hosts this app. This value must match what's configured in the Connected App. | `https://YOUR_HOST/auth/callback` |
44 | | `SF_CONSUMER_KEY` | Connected app consumer key. | _secret_ |
45 | | `SF_CONSUMER_SECRET` | Connected app consumer secret. | _secret_ |
46 | | `SF_API_VERSION` | Salesforce API version. | `54.0` |
47 | | `AWS_ACCESS_KEY_ID` | Access key ID for your AWS IAM user. | _secret_ |
48 | | `AWS_SECRET_ACCESS_KEY` | Secret access key for your AWS IAM user. | _secret_ |
49 | | `AWS_REGION` | Region of your S3 bucket. | `eu-west-3` |
50 | | `AWS_S3_BUCKET` | Name of your S3 bucket. | `poz-sf-demo` |
51 | | `SESSION_SECRET` | Secret key for signing the session cookie with a length of 32 characters or more. | _secret_ |
52 | | `SESSION_DURATION` | Salesforce session duration in minutes (default is 120 minutes). | `120` |
53 |
54 | If you are testing locally, you can create a `.env` file at the root of the project with this template:
55 |
56 | ```properties
57 | SF_LOGIN_URL=https://login.salesforce.com
58 | SF_AUTH_CALLBACK_URL=https://YOUR_HOST/auth/callback
59 | SF_CONSUMER_KEY=
60 | SF_CONSUMER_SECRET=
61 | SF_API_VERSION=54.0
62 |
63 | AWS_ACCESS_KEY_ID=
64 | AWS_SECRET_ACCESS_KEY=
65 | AWS_REGION=
66 | AWS_S3_BUCKET=
67 |
68 | SESSION_SECRET=
69 | SESSION_DURATION=120
70 | ```
71 |
72 | 1. Run `npm start` to start the app.
73 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | const jsforce = require('jsforce');
2 | const fastify = require('fastify');
3 | const fastifySession = require('@fastify/session');
4 | const fastifyCookie = require('@fastify/cookie');
5 | const {
6 | S3Client,
7 | HeadObjectCommand,
8 | GetObjectCommand
9 | } = require('@aws-sdk/client-s3');
10 |
11 | // Check and retrieve environment variables
12 | require('dotenv').config();
13 | [
14 | 'SF_LOGIN_URL',
15 | 'SF_AUTH_CALLBACK_URL',
16 | 'SF_CONSUMER_KEY',
17 | 'SF_CONSUMER_SECRET',
18 | 'SF_API_VERSION',
19 | 'AWS_ACCESS_KEY_ID',
20 | 'AWS_SECRET_ACCESS_KEY',
21 | 'AWS_REGION',
22 | 'AWS_S3_BUCKET',
23 | 'SESSION_SECRET'
24 | ].forEach((varName) => {
25 | if (!process.env[varName]) {
26 | console.error(`Missing ${varName} environment variable`);
27 | process.exit(-1);
28 | }
29 | });
30 | const {
31 | SF_LOGIN_URL,
32 | SF_AUTH_CALLBACK_URL,
33 | SF_CONSUMER_KEY,
34 | SF_CONSUMER_SECRET,
35 | SF_API_VERSION,
36 | AWS_REGION,
37 | AWS_S3_BUCKET,
38 | SESSION_SECRET,
39 | SESSION_DURATION
40 | } = process.env;
41 |
42 | // Get session settings
43 | const maxAge = SESSION_DURATION
44 | ? parseInt(SESSION_DURATION, 10) * 60 * 1000
45 | : 120 * 60 * 1000;
46 | const secure = SF_AUTH_CALLBACK_URL.startsWith('https://');
47 |
48 | // Prepare server
49 | const app = fastify({ logger: true });
50 | app.register(fastifyCookie);
51 | app.register(fastifySession, {
52 | secret: SESSION_SECRET,
53 | maxAge,
54 | cookie: { secure }
55 | });
56 |
57 | // Prepare Salesforce client OAuth configuration
58 | const oauth2 = new jsforce.OAuth2({
59 | loginUrl: SF_LOGIN_URL,
60 | clientId: SF_CONSUMER_KEY,
61 | clientSecret: SF_CONSUMER_SECRET,
62 | redirectUri: SF_AUTH_CALLBACK_URL
63 | });
64 |
65 | /**
66 | * Attemps to retrieves the server session.
67 | * If there is no session, redirects to the login/authorization URL
68 | */
69 | function checkAndRetrieveSalesforceClient(request, response) {
70 | const { session } = request;
71 | if (!session.accessToken) {
72 | // Save original URL for redirect after auth
73 | session.orginalUrl = `${request.protocol}://${request.hostname}${request.url}`;
74 | // Redirect to Salesforce login/authorization URL
75 | response.redirect(oauth2.getAuthorizationUrl({ scope: 'api' }));
76 | return null;
77 | } else {
78 | session.touch(); // Keep session alive
79 | return new jsforce.Connection({
80 | instanceUrl: session.instanceUrl,
81 | accessToken: session.accessToken,
82 | version: SF_API_VERSION
83 | });
84 | }
85 | }
86 |
87 | /**
88 | * Checks permissions and downloads the requested file from S3
89 | */
90 | async function downloadFile(sfClient, s3Key, response) {
91 | // Get S3 file metadata
92 | const s3Client = new S3Client({ region: AWS_REGION });
93 | const s3Input = {
94 | Bucket: AWS_S3_BUCKET,
95 | Key: s3Key
96 | };
97 | const s3Metatada = await s3Client.send(new HeadObjectCommand(s3Input));
98 | const entityId = s3Metatada.Metadata['sfdc-linked-entity-id'];
99 | //const ownerId = s3Metatada.Metadata['sfdc-owner-id'];
100 | const entityApiName = s3Metatada.Metadata['sfdc-linked-entity-api-name'];
101 | const fileName = s3Key.substring(entityId.length + 1); // Remove entity Id and slash
102 |
103 | // Check read permission by trying to access Salesforce record with current user
104 | await testSfRecordPermissions(sfClient, entityApiName, entityId);
105 |
106 | // Download S3 file
107 | response.raw.setHeader(
108 | 'Content-Disposition',
109 | `attachment; filename="${fileName}"`
110 | );
111 | response.raw.setHeader('Content-Type', s3Metatada.ContentType);
112 | response.raw.setHeader('Content-Length', s3Metatada.ContentLength);
113 | const byteStream = await s3Client.send(new GetObjectCommand(s3Input));
114 | byteStream.Body.pipe(response.raw);
115 | }
116 |
117 | async function testSfRecordPermissions(sfClient, entityApiName, entityId) {
118 | return new Promise((resolve, reject) => {
119 | sfClient.sobject(entityApiName).retrieve(entityId, (err, record) => {
120 | if (err) {
121 | reject(err);
122 | } else {
123 | resolve();
124 | }
125 | });
126 | });
127 | }
128 |
129 | /**
130 | * Login callback endpoint (only called by Salesforce)
131 | */
132 | app.get('/auth/callback', (request, response) => {
133 | if (!request.query.code) {
134 | response
135 | .code(500)
136 | .send('Failed to get authorization code from server callback.');
137 | return;
138 | }
139 | if (!request.session.orginalUrl) {
140 | response.code(500).send('Failed to retrieve download URL.');
141 | return;
142 | }
143 |
144 | // Authenticate with OAuth
145 | const sfClient = new jsforce.Connection({
146 | oauth2,
147 | version: SF_API_VERSION
148 | });
149 | sfClient.authorize(request.query.code, (error, userInfo) => {
150 | if (error) {
151 | app.log.error(
152 | 'Salesforce authorization error: ' + JSON.stringify(error)
153 | );
154 | response.code(500).serialize(error);
155 | return;
156 | }
157 | app.log.info(`Logged in Salesforce as user ${userInfo.id}`);
158 |
159 | // Store OAuth session data in server (never expose it directly to client)
160 | const { session } = request;
161 | session.instanceUrl = sfClient.instanceUrl;
162 | session.accessToken = sfClient.accessToken;
163 | session.userId = userInfo.id;
164 |
165 | // Redirect to original URL
166 | const urlString = session.orginalUrl;
167 | session.orginalUrl = undefined;
168 | response.redirect(urlString);
169 | });
170 | });
171 |
172 | app.get('/download', (request, response) => {
173 | const sfClient = checkAndRetrieveSalesforceClient(request, response);
174 | if (sfClient) {
175 | // Parse download URL
176 | const downloadUrl = new URL(
177 | `${request.protocol}://${request.hostname}${request.url}`
178 | );
179 | const s3UrlString = downloadUrl.searchParams.get('url');
180 | const s3Key = new URL(s3UrlString).pathname.substring(1);
181 | // Download file
182 | app.log.info(
183 | `User ${request.session.userId} attempting to download ${s3UrlString}`
184 | );
185 | downloadFile(sfClient, s3Key, response);
186 | }
187 | });
188 |
189 | // Start the server
190 | const start = async () => {
191 | try {
192 | await app.listen(process.env.PORT ? process.env.PORT : 3000, '0.0.0.0');
193 | } catch (err) {
194 | app.log.error(err);
195 | process.exit(1);
196 | }
197 | };
198 | start();
199 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Creative Commons Legal Code
2 |
3 | CC0 1.0 Universal
4 |
5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12 | HEREUNDER.
13 |
14 | Statement of Purpose
15 |
16 | The laws of most jurisdictions throughout the world automatically confer
17 | exclusive Copyright and Related Rights (defined below) upon the creator
18 | and subsequent owner(s) (each and all, an "owner") of an original work of
19 | authorship and/or a database (each, a "Work").
20 |
21 | Certain owners wish to permanently relinquish those rights to a Work for
22 | the purpose of contributing to a commons of creative, cultural and
23 | scientific works ("Commons") that the public can reliably and without fear
24 | of later claims of infringement build upon, modify, incorporate in other
25 | works, reuse and redistribute as freely as possible in any form whatsoever
26 | and for any purposes, including without limitation commercial purposes.
27 | These owners may contribute to the Commons to promote the ideal of a free
28 | culture and the further production of creative, cultural and scientific
29 | works, or to gain reputation or greater distribution for their Work in
30 | part through the use and efforts of others.
31 |
32 | For these and/or other purposes and motivations, and without any
33 | expectation of additional consideration or compensation, the person
34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35 | is an owner of Copyright and Related Rights in the Work, voluntarily
36 | elects to apply CC0 to the Work and publicly distribute the Work under its
37 | terms, with knowledge of his or her Copyright and Related Rights in the
38 | Work and the meaning and intended legal effect of CC0 on those rights.
39 |
40 | 1. Copyright and Related Rights. A Work made available under CC0 may be
41 | protected by copyright and related or neighboring rights ("Copyright and
42 | Related Rights"). Copyright and Related Rights include, but are not
43 | limited to, the following:
44 |
45 | i. the right to reproduce, adapt, distribute, perform, display,
46 | communicate, and translate a Work;
47 | ii. moral rights retained by the original author(s) and/or performer(s);
48 | iii. publicity and privacy rights pertaining to a person's image or
49 | likeness depicted in a Work;
50 | iv. rights protecting against unfair competition in regards to a Work,
51 | subject to the limitations in paragraph 4(a), below;
52 | v. rights protecting the extraction, dissemination, use and reuse of data
53 | in a Work;
54 | vi. database rights (such as those arising under Directive 96/9/EC of the
55 | European Parliament and of the Council of 11 March 1996 on the legal
56 | protection of databases, and under any national implementation
57 | thereof, including any amended or successor version of such
58 | directive); and
59 | vii. other similar, equivalent or corresponding rights throughout the
60 | world based on applicable law or treaty, and any national
61 | implementations thereof.
62 |
63 | 2. Waiver. To the greatest extent permitted by, but not in contravention
64 | of, applicable law, Affirmer hereby overtly, fully, permanently,
65 | irrevocably and unconditionally waives, abandons, and surrenders all of
66 | Affirmer's Copyright and Related Rights and associated claims and causes
67 | of action, whether now known or unknown (including existing as well as
68 | future claims and causes of action), in the Work (i) in all territories
69 | worldwide, (ii) for the maximum duration provided by applicable law or
70 | treaty (including future time extensions), (iii) in any current or future
71 | medium and for any number of copies, and (iv) for any purpose whatsoever,
72 | including without limitation commercial, advertising or promotional
73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74 | member of the public at large and to the detriment of Affirmer's heirs and
75 | successors, fully intending that such Waiver shall not be subject to
76 | revocation, rescission, cancellation, termination, or any other legal or
77 | equitable action to disrupt the quiet enjoyment of the Work by the public
78 | as contemplated by Affirmer's express Statement of Purpose.
79 |
80 | 3. Public License Fallback. Should any part of the Waiver for any reason
81 | be judged legally invalid or ineffective under applicable law, then the
82 | Waiver shall be preserved to the maximum extent permitted taking into
83 | account Affirmer's express Statement of Purpose. In addition, to the
84 | extent the Waiver is so judged Affirmer hereby grants to each affected
85 | person a royalty-free, non transferable, non sublicensable, non exclusive,
86 | irrevocable and unconditional license to exercise Affirmer's Copyright and
87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the
88 | maximum duration provided by applicable law or treaty (including future
89 | time extensions), (iii) in any current or future medium and for any number
90 | of copies, and (iv) for any purpose whatsoever, including without
91 | limitation commercial, advertising or promotional purposes (the
92 | "License"). The License shall be deemed effective as of the date CC0 was
93 | applied by Affirmer to the Work. Should any part of the License for any
94 | reason be judged legally invalid or ineffective under applicable law, such
95 | partial invalidity or ineffectiveness shall not invalidate the remainder
96 | of the License, and in such case Affirmer hereby affirms that he or she
97 | will not (i) exercise any of his or her remaining Copyright and Related
98 | Rights in the Work or (ii) assert any associated claims and causes of
99 | action with respect to the Work, in either case contrary to Affirmer's
100 | express Statement of Purpose.
101 |
102 | 4. Limitations and Disclaimers.
103 |
104 | a. No trademark or patent rights held by Affirmer are waived, abandoned,
105 | surrendered, licensed or otherwise affected by this document.
106 | b. Affirmer offers the Work as-is and makes no representations or
107 | warranties of any kind concerning the Work, express, implied,
108 | statutory or otherwise, including without limitation warranties of
109 | title, merchantability, fitness for a particular purpose, non
110 | infringement, or the absence of latent or other defects, accuracy, or
111 | the present or absence of errors, whether or not discoverable, all to
112 | the greatest extent permissible under applicable law.
113 | c. Affirmer disclaims responsibility for clearing rights of other persons
114 | that may apply to the Work or any use thereof, including without
115 | limitation any person's Copyright and Related Rights in the Work.
116 | Further, Affirmer disclaims responsibility for obtaining any necessary
117 | consents, permissions or other rights required for any use of the
118 | Work.
119 | d. Affirmer understands and acknowledges that Creative Commons is not a
120 | party to this document and has no duty or obligation with respect to
121 | this CC0 or use of the Work.
122 |
--------------------------------------------------------------------------------