Skip to content

Commit 05824a7

Browse files
authored
fix: embed transformation params in the signed url token (#229)
1 parent fd84189 commit 05824a7

10 files changed

Lines changed: 104 additions & 25 deletions

File tree

‎src/auth/jwt.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ interface jwtInterface {
1010

1111
export type SignedToken = {
1212
url: string
13+
transformations?: string
1314
}
1415

1516
/**

‎src/http/error-handler.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,6 @@ export const setErrorHandler = (app: FastifyInstance) => {
1414
// it will be logged in the request log plugin
1515
reply.executionError = error
1616

17-
request.log.error({ error }, `request error | ${request.id}`)
18-
1917
if (process.env.NODE_ENV !== 'production') {
2018
console.error(error)
2119
}

‎src/http/routes/object/getSignedURL.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { FastifyInstance } from 'fastify'
22
import { FromSchema } from 'json-schema-to-ts'
33
import { createDefaultSchema } from '../../generic-routes'
44
import { AuthenticatedRequest } from '../../request'
5+
import { ImageRenderer } from '../../../storage/renderer'
6+
import { transformationQueryString } from '../../schemas/transformations'
57

68
const getSignedURLParamsSchema = {
79
type: 'object',
@@ -18,6 +20,12 @@ const getSignedURLBodySchema = {
1820
},
1921
required: ['expiresIn'],
2022
} as const
23+
const renderImageQuerySchema = {
24+
type: 'object',
25+
properties: {
26+
...transformationQueryString,
27+
},
28+
} as const
2129
const successResponseSchema = {
2230
type: 'object',
2331
properties: {
@@ -33,6 +41,7 @@ const successResponseSchema = {
3341
interface getSignedURLRequestInterface extends AuthenticatedRequest {
3442
Params: FromSchema<typeof getSignedURLParamsSchema>
3543
Body: FromSchema<typeof getSignedURLBodySchema>
44+
Querystring: FromSchema<typeof renderImageQuerySchema>
3645
}
3746

3847
export default async function routes(fastify: FastifyInstance) {
@@ -41,6 +50,7 @@ export default async function routes(fastify: FastifyInstance) {
4150
const schema = createDefaultSchema(successResponseSchema, {
4251
body: getSignedURLBodySchema,
4352
params: getSignedURLParamsSchema,
53+
querystring: renderImageQuerySchema,
4454
summary,
4555
tags: ['object'],
4656
})
@@ -55,9 +65,13 @@ export default async function routes(fastify: FastifyInstance) {
5565
const objectName = request.params['*']
5666
const { expiresIn } = request.body
5767

68+
const urlPath = request.url.split('?').shift()
69+
5870
const signedURL = await request.storage
5971
.from(bucketName)
60-
.signObjectUrl(objectName, request.url, expiresIn)
72+
.signObjectUrl(objectName, urlPath as string, expiresIn, {
73+
transformations: ImageRenderer.applyTransformation(request.query || {}).join(','),
74+
})
6175

6276
return response.status(200).send({ signedURL })
6377
}

‎src/http/routes/render/renderAuthenticatedImage.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { getConfig } from '../../../config'
22
import { FromSchema } from 'json-schema-to-ts'
33
import { FastifyInstance } from 'fastify'
44
import { ImageRenderer } from '../../../storage/renderer'
5+
import { transformationQueryString } from '../../schemas/transformations'
56

67
const { globalS3Bucket } = getConfig()
78

@@ -17,9 +18,7 @@ const renderAuthenticatedImageParamsSchema = {
1718
const renderImageQuerySchema = {
1819
type: 'object',
1920
properties: {
20-
height: { type: 'integer', examples: [100], minimum: 0 },
21-
width: { type: 'integer', examples: [100], minimum: 0 },
22-
resize: { type: 'string', enum: ['fill', 'fit', 'fill-down', 'force', 'auto'] },
21+
...transformationQueryString,
2322
download: { type: 'string' },
2423
},
2524
} as const

‎src/http/routes/render/renderPublicImage.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { getConfig } from '../../../config'
22
import { FromSchema } from 'json-schema-to-ts'
33
import { FastifyInstance } from 'fastify'
44
import { ImageRenderer } from '../../../storage/renderer'
5+
import { transformationQueryString } from '../../schemas/transformations'
56

67
const { globalS3Bucket } = getConfig()
78

@@ -18,9 +19,7 @@ const renderPublicImageParamsSchema = {
1819
const renderImageQuerySchema = {
1920
type: 'object',
2021
properties: {
21-
height: { type: 'integer', examples: [100], minimum: 0 },
22-
width: { type: 'integer', examples: [100], minimum: 0 },
23-
resize: { type: 'string', enum: ['fill', 'fit', 'fill-down', 'force', 'auto'] },
22+
...transformationQueryString,
2423
download: { type: 'string' },
2524
},
2625
} as const

‎src/http/routes/render/renderSignedImage.ts‎

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,6 @@ const renderAuthenticatedImageParamsSchema = {
1919
const renderImageQuerySchema = {
2020
type: 'object',
2121
properties: {
22-
height: { type: 'integer', examples: [100], minimum: 0 },
23-
width: { type: 'integer', examples: [100], minimum: 0 },
24-
resize: { type: 'string', enum: ['fill', 'fit', 'fill-down', 'force', 'auto'] },
2522
token: { type: 'string' },
2623
download: { type: 'string' },
2724
},
@@ -36,7 +33,7 @@ interface renderImageRequestInterface {
3633
export default async function routes(fastify: FastifyInstance) {
3734
const summary = 'Render an authenticated image with the given transformations'
3835
fastify.get<renderImageRequestInterface>(
39-
'/signed/:bucketName/*',
36+
'/sign/:bucketName/*',
4037
{
4138
schema: {
4239
params: renderAuthenticatedImageParamsSchema,
@@ -60,17 +57,18 @@ export default async function routes(fastify: FastifyInstance) {
6057
throw new StorageBackendError('Invalid JWT', 400, err.message, err)
6158
}
6259

63-
const { url } = payload
60+
const { url, transformations } = payload
6461
const s3Key = `${request.tenantId}/${url}`
6562
request.log.info(s3Key)
6663

6764
const renderer = request.storage.renderer('image') as ImageRenderer
68-
69-
return renderer.setTransformations(request.query).render(request, response, {
70-
bucket: globalS3Bucket,
71-
key: s3Key,
72-
download,
73-
})
65+
return renderer
66+
.setTransformationsFromString(transformations || '')
67+
.render(request, response, {
68+
bucket: globalS3Bucket,
69+
key: s3Key,
70+
download,
71+
})
7472
}
7573
)
7674
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export const transformationQueryString = {
2+
height: { type: 'integer', examples: [100], minimum: 0 },
3+
width: { type: 'integer', examples: [100], minimum: 0 },
4+
resize: { type: 'string', enum: ['fill', 'fit', 'fill-down', 'force', 'auto'] },
5+
} as const

‎src/storage/object.ts‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -370,17 +370,30 @@ export class ObjectStorage {
370370
* @param objectName
371371
* @param url
372372
* @param expiresIn seconds
373+
* @param metadata
373374
*/
374-
async signObjectUrl(objectName: string, url: string, expiresIn: number) {
375+
async signObjectUrl(
376+
objectName: string,
377+
url: string,
378+
expiresIn: number,
379+
metadata?: Record<string, string>
380+
) {
375381
await this.findObject(objectName)
382+
metadata = metadata ?? {}
376383

377384
const urlParts = url.split('/')
378385
const urlToSign = decodeURI(urlParts.splice(3).join('/'))
379386
const jwtSecret = await getJwtSecret(this.db.tenantId)
380-
const token = await signJWT({ url: urlToSign }, jwtSecret, expiresIn)
387+
const token = await signJWT({ url: urlToSign, ...metadata }, jwtSecret, expiresIn)
388+
389+
let urlPath = 'object'
390+
391+
if (metadata?.transformations) {
392+
urlPath = 'render/image'
393+
}
381394

382395
// @todo parse the url properly
383-
return `/object/sign/${urlToSign}?token=${token}`
396+
return `/${urlPath}/sign/${urlToSign}?token=${token}`
384397
}
385398

386399
/**

‎src/storage/renderer/image.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { StorageBackendAdapter, ObjectMetadata } from '../backend'
1+
import { ObjectMetadata, StorageBackendAdapter } from '../backend'
22
import axios, { Axios, AxiosError } from 'axios'
33
import { getConfig } from '../../config'
44
import { FastifyRequest } from 'fastify'
@@ -80,6 +80,27 @@ export class ImageRenderer extends Renderer {
8080
return this
8181
}
8282

83+
setTransformationsFromString(transformations: string) {
84+
const params = transformations.split(',')
85+
86+
this.transformOptions = params.reduce((all, param) => {
87+
const [name, value] = param.split(':') as [keyof TransformOptions, any]
88+
switch (name) {
89+
case 'height':
90+
all.height = parseInt(value, 10)
91+
break
92+
case 'width':
93+
all.width = parseInt(value, 10)
94+
break
95+
case 'resize':
96+
all.resize = value
97+
}
98+
return all
99+
}, {} as TransformOptions)
100+
101+
return this
102+
}
103+
83104
/**
84105
* Fetch the transformed asset from imgproxy.
85106
* We use a secure signed url in order for imgproxy to download and
@@ -134,7 +155,7 @@ export class ImageRenderer extends Renderer {
134155
* Applies whitelisted transformations with specific limits applied
135156
* @param options
136157
*/
137-
static applyTransformation(options: TransformOptions) {
158+
static applyTransformation(options: TransformOptions): string[] {
138159
const segments = []
139160

140161
if (options.height) {

‎src/test/render-routes.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,4 +65,35 @@ describe('image rendering routes', () => {
6565
{ responseType: 'stream' }
6666
)
6767
})
68+
69+
it('will render a transformed image providing a signed url', async () => {
70+
const signURLResponse = await app().inject({
71+
method: 'POST',
72+
url: '/object/sign/bucket2/authenticated/casestudy.png?width=100&height=100',
73+
payload: {
74+
expiresIn: 60000,
75+
},
76+
headers: {
77+
authorization: `Bearer ${process.env.SERVICE_KEY}`,
78+
},
79+
})
80+
81+
const signedURLBody = signURLResponse.json<{ signedURL: string }>()
82+
83+
const testAxios = axios.create({ baseURL: imgProxyURL })
84+
jest.spyOn(ImageRenderer.prototype, 'getClient').mockReturnValue(testAxios)
85+
const axiosSpy = jest.spyOn(testAxios, 'get')
86+
87+
const response = await app().inject({
88+
method: 'GET',
89+
url: signedURLBody.signedURL,
90+
})
91+
92+
expect(response.statusCode).toBe(200)
93+
expect(S3Backend.prototype.privateAssetUrl).toBeCalledTimes(1)
94+
expect(axiosSpy).toBeCalledWith(
95+
'/public/height:100/width:100/resizing_type:fill/plain/local:///data/sadcat.jpg',
96+
{ responseType: 'stream' }
97+
)
98+
})
6899
})

0 commit comments

Comments
 (0)