|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const firebaseFunctions = require('firebase-functions'); |
| 4 | +const firebaseAdmin = require('firebase-admin'); |
| 5 | +const gcs = require('@google-cloud/storage')(); |
| 6 | +const jwt = require('jsonwebtoken'); |
| 7 | +const fs = require('fs'); |
| 8 | + |
| 9 | +/** |
| 10 | + * Data and images handling for Screenshot test. |
| 11 | + * |
| 12 | + * All users can post data to temporary folder. These Functions will check the data with JsonWebToken and |
| 13 | + * move the valid data out of temporary folder. |
| 14 | + * |
| 15 | + * For valid data posted to database /$temp/screenshot/reports/$prNumber/$secureToken, move it to |
| 16 | + * /screenshot/reports/$prNumber. |
| 17 | + * These are data for screenshot results (success or failure), GitHub PR/commit and TravisCI job information |
| 18 | + * |
| 19 | + * For valid image results written to database /$temp/screenshot/images/$prNumber/$secureToken/, save the image |
| 20 | + * data to image files and upload to google cloud storage under location /screenshots/$prNumber |
| 21 | + * These are screenshot test result images, and difference images generated from screenshot comparison. |
| 22 | + * |
| 23 | + * For golden images uploaded to /goldens, read the data from images files and write the data to Firebase database |
| 24 | + * under location /screenshot/goldens |
| 25 | + * Screenshot tests can only read restricted database data with no credentials, and they cannot access |
| 26 | + * Google Cloud Storage. Therefore we copy the image data to database to make it available to screenshot tests. |
| 27 | + * |
| 28 | + * The JWT is stored in the data path, so every write to database needs a valid JWT to be copied to database/storage. |
| 29 | + * All invalid data will be removed. |
| 30 | + * The JWT has 3 parts: header, payload and signature. These three parts are joint by '/' in path. |
| 31 | + */ |
| 32 | + |
| 33 | +// Initailize the admin app |
| 34 | +firebaseAdmin.initializeApp(firebaseFunctions.config().firebase); |
| 35 | + |
| 36 | +/** The valid data types database accepts */ |
| 37 | +const dataTypes = ['filenames', 'commit', 'result', 'sha', 'travis']; |
| 38 | + |
| 39 | +/** The repo slug. This is used to validate the JWT is sent from correct repo. */ |
| 40 | +const repoSlug = firebaseFunctions.config().repo.slug; |
| 41 | + |
| 42 | +/** The JWT secret. This is used to validate JWT. */ |
| 43 | +const secret = firebaseFunctions.config().secret.key; |
| 44 | + |
| 45 | +/** The storage bucket to store the images. The bucket is also used by Firebase Storage. */ |
| 46 | +const bucket = gcs.bucket(firebaseFunctions.config().firebase.storageBucket); |
| 47 | + |
| 48 | +/** The Json Web Token format. The token is stored in data path. */ |
| 49 | +const jwtFormat = '{jwtHeader}/{jwtPayload}/{jwtSignature}'; |
| 50 | + |
| 51 | +/** The temporary folder name for screenshot data that needs to be validated via JWT. */ |
| 52 | +const tempFolder = '/untrustedInbox'; |
| 53 | + |
| 54 | +/** |
| 55 | + * Copy valid data from /$temp/screenshot/reports/$prNumber/$secureToken/ to /screenshot/reports/$prNumber |
| 56 | + * Data copied: filenames(image results names), commit(github PR info), |
| 57 | + * sha (github PR info), result (true or false for all the tests), travis job number |
| 58 | + */ |
| 59 | +const copyDataPath = `${tempFolder}/screenshot/reports/{prNumber}/${jwtFormat}/{dataType}`; |
| 60 | +exports.copyData = firebaseFunctions.database.ref(copyDataPath).onWrite(event => { |
| 61 | + const dataType = event.params.dataType; |
| 62 | + if (dataTypes.includes(dataType)) { |
| 63 | + return verifyAndCopyScreenshotResult(event, dataType); |
| 64 | + } |
| 65 | +}); |
| 66 | + |
| 67 | +/** |
| 68 | + * Copy valid data from /$temp/screenshot/reports/$prNumber/$secureToken/ to /screenshot/reports/$prNumber |
| 69 | + * Data copied: test result for each file/test with ${filename}. The value should be true or false. |
| 70 | + */ |
| 71 | +const copyDataResultPath = `${tempFolder}/screenshot/reports/{prNumber}/${jwtFormat}/results/{filename}`; |
| 72 | +exports.copyDataResult = firebaseFunctions.database.ref(copyDataResultPath).onWrite(event => { |
| 73 | + return verifyAndCopyScreenshotResult(event, `results/${event.params.filename}`); |
| 74 | +}); |
| 75 | + |
| 76 | +/** |
| 77 | + * Copy valid data from database /$temp/screenshot/images/$prNumber/$secureToken/ to storage /screenshots/$prNumber |
| 78 | + * Data copied: test result images. Convert from data to image files in storage. |
| 79 | + */ |
| 80 | +const copyImagePath = `${tempFolder}/screenshot/images/{prNumber}/${jwtFormat}/{dataType}/{filename}`; |
| 81 | +exports.copyImage = firebaseFunctions.database.ref(copyImagePath).onWrite(event => { |
| 82 | + // Only edit data when it is first created. Exit when the data is deleted. |
| 83 | + if (event.data.previous.exists() || !event.data.exists()) { |
| 84 | + return; |
| 85 | + } |
| 86 | + |
| 87 | + const dataType = event.params.dataType; |
| 88 | + const prNumber = event.params.prNumber; |
| 89 | + const secureToken = getSecureToken(event); |
| 90 | + const saveFilename = `${event.params.filename}.screenshot.png`; |
| 91 | + |
| 92 | + if (dataType != 'diff' && dataType != 'test') { |
| 93 | + return; |
| 94 | + } |
| 95 | + |
| 96 | + return verifySecureToken(secureToken, prNumber).then((payload) => { |
| 97 | + const tempPath = `/tmp/${dataType}-${saveFilename}` |
| 98 | + const filePath = `screenshots/${prNumber}/${dataType}/${saveFilename}`; |
| 99 | + const binaryData = new Buffer(event.data.val(), 'base64').toString('binary'); |
| 100 | + fs.writeFile(tempPath, binaryData, 'binary'); |
| 101 | + return bucket.upload(tempPath, {destination: filePath}).then(() => { |
| 102 | + // Clear the data in temporary folder after processed. |
| 103 | + return event.data.ref.parent.set(null); |
| 104 | + }); |
| 105 | + }).catch((error) => { |
| 106 | + console.error(`Invalid secure token ${secureToken} ${error}`); |
| 107 | + return event.data.ref.parent.set(null); |
| 108 | + }); |
| 109 | +}); |
| 110 | + |
| 111 | +/** |
| 112 | + * Copy valid goldens from storage /goldens/ to database /screenshot/goldens/ |
| 113 | + * so we can read the goldens without credentials. |
| 114 | + */ |
| 115 | +exports.copyGoldens = firebaseFunctions.storage.bucket(firebaseFunctions.config().firebase.storageBucket) |
| 116 | + .object().onChange(event => { |
| 117 | + // The filePath should always l ook like "goldens/xxx.png" |
| 118 | + const filePath = event.data.name; |
| 119 | + |
| 120 | + // Get the file name. |
| 121 | + const fileNames = filePath.split('/'); |
| 122 | + if (fileNames.length != 2 && fileNames[0] != 'goldens') { |
| 123 | + return; |
| 124 | + } |
| 125 | + const filenameKey = fileNames[1].replace('.screenshot.png', ''); |
| 126 | + |
| 127 | + // When a gold image is deleted, also delete the corresponding record in the firebase database. |
| 128 | + if (event.data.resourceState === 'not_exists') { |
| 129 | + return firebaseAdmin.database().ref(`screenshot/goldens/${filenameKey}`).set(null); |
| 130 | + } |
| 131 | + |
| 132 | + // Download file from bucket. |
| 133 | + const bucket = gcs.bucket(event.data.bucket); |
| 134 | + const tempFilePath = `/tmp/${fileNames[1]}`; |
| 135 | + return bucket.file(filePath).download({destination: tempFilePath}).then(() => { |
| 136 | + const data = fs.readFileSync(tempFilePath); |
| 137 | + return firebaseAdmin.database().ref(`screenshot/goldens/${filenameKey}`).set(data); |
| 138 | + }); |
| 139 | +}); |
| 140 | + |
| 141 | +/** |
| 142 | + * Handle data written to temporary folder. Validate the JWT and move the data out of |
| 143 | + * temporary folder if the token is valid. |
| 144 | + */ |
| 145 | +function verifyAndCopyScreenshotResult(event, path) { |
| 146 | + // Only edit data when it is first created. Exit when the data is deleted. |
| 147 | + if (event.data.previous.exists() || !event.data.exists()) { |
| 148 | + return; |
| 149 | + } |
| 150 | + |
| 151 | + const prNumber = event.params.prNumber; |
| 152 | + const secureToken = getSecureToken(event); |
| 153 | + const original = event.data.val(); |
| 154 | + |
| 155 | + return verifySecureToken(secureToken, prNumber).then((payload) => { |
| 156 | + return firebaseAdmin.database().ref().child('screenshot/reports') |
| 157 | + .child(prNumber).child(path).set(original).then(() => { |
| 158 | + // Clear the data in temporary folder after processed. |
| 159 | + return event.data.ref.parent.set(null); |
| 160 | + }); |
| 161 | + }).catch((error) => { |
| 162 | + console.error(`Invalid secure token ${secureToken} ${error}`); |
| 163 | + return event.data.ref.parent.set(null); |
| 164 | + }); |
| 165 | +} |
| 166 | + |
| 167 | +/** |
| 168 | + * Extract the Json Web Token from event params. |
| 169 | + * In screenshot gulp task the path we use is {jwtHeader}/{jwtPayload}/{jwtSignature}. |
| 170 | + * Replace '/' with '.' to get the token. |
| 171 | + */ |
| 172 | +function getSecureToken(event) { |
| 173 | + return `${event.params.jwtHeader}.${event.params.jwtPayload}.${event.params.jwtSignature}`; |
| 174 | +} |
| 175 | + |
| 176 | +function verifySecureToken(token, prNumber) { |
| 177 | + return new Promise((resolve, reject) => { |
| 178 | + jwt.verify(token, secret, {issuer: 'Travis CI, GmbH'}, (err, payload) => { |
| 179 | + if (err) { |
| 180 | + reject(err.message || err); |
| 181 | + } else if (payload.slug !== repoSlug) { |
| 182 | + reject(`jwt slug invalid. expected: ${repoSlug}`); |
| 183 | + } else if (payload['pull-request'].toString() !== prNumber) { |
| 184 | + reject(`jwt pull-request invalid. expected: ${prNumber} actual: ${payload['pull-request']}`); |
| 185 | + } else { |
| 186 | + resolve(payload); |
| 187 | + } |
| 188 | + }); |
| 189 | + }); |
| 190 | +} |
0 commit comments