Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(plugin-cloud): refresh session on ExpiredToken error code #8904

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions packages/payload-cloud/src/staticHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { CollectionCachingConfig, PluginOptions, StaticHandler } from './ty

import { createKey } from './utilities/createKey.js'
import { getStorageClient } from './utilities/getStorageClient.js'
import { refreshSession } from './utilities/refreshSession.js'

interface Args {
cachingOptions?: PluginOptions['uploadCaching']
Expand Down Expand Up @@ -46,10 +47,25 @@ export const getStaticHandler = ({ cachingOptions, collection }: Args): StaticHa
identityID,
})

const object = await storageClient.getObject({
Bucket: process.env.PAYLOAD_CLOUD_BUCKET,
Key,
})
let object
try {
object = await storageClient.getObject({
Bucket: process.env.PAYLOAD_CLOUD_BUCKET,
Key,
})
} catch (err: any) {
if (err.code === 'ExpiredToken' || err.Code === 'ExpiredToken') {
await refreshSession()

const { storageClient: newStorageClient } = await getStorageClient()
object = await newStorageClient.getObject({
Bucket: process.env.PAYLOAD_CLOUD_BUCKET,
Key,
})
} else {
throw err
}
}

if (!object.Body) {
return new Response(null, { status: 404, statusText: 'Not Found' })
Expand Down
40 changes: 3 additions & 37 deletions packages/payload-cloud/src/utilities/getStorageClient.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,11 @@
import type { CognitoUserSession } from 'amazon-cognito-identity-js'

import { CognitoIdentityClient } from '@aws-sdk/client-cognito-identity'
import * as AWS from '@aws-sdk/client-s3'
import { fromCognitoIdentityPool } from '@aws-sdk/credential-providers'

import { authAsCognitoUser } from './authAsCognitoUser.js'
import type * as AWS from '@aws-sdk/client-s3'

export type GetStorageClient = () => Promise<{
identityID: string
storageClient: AWS.S3
}>

let storageClient: AWS.S3 | null = null
let session: CognitoUserSession | null = null
let identityID: string
import { identityID, refreshSession, session, storageClient } from './refreshSession.js'

export const getStorageClient: GetStorageClient = async () => {
if (storageClient && session?.isValid()) {
Expand All @@ -23,33 +15,7 @@ export const getStorageClient: GetStorageClient = async () => {
}
}

session = await authAsCognitoUser(
process.env.PAYLOAD_CLOUD_PROJECT_ID,
process.env.PAYLOAD_CLOUD_COGNITO_PASSWORD,
)

const cognitoIdentity = new CognitoIdentityClient({
credentials: fromCognitoIdentityPool({
clientConfig: {
region: 'us-east-1',
},
identityPoolId: process.env.PAYLOAD_CLOUD_COGNITO_IDENTITY_POOL_ID,
logins: {
[`cognito-idp.us-east-1.amazonaws.com/${process.env.PAYLOAD_CLOUD_COGNITO_USER_POOL_ID}`]:
session.getIdToken().getJwtToken(),
},
}),
})

const credentials = await cognitoIdentity.config.credentials()

// @ts-expect-error - Incorrect AWS types
identityID = credentials.identityId

storageClient = new AWS.S3({
credentials,
region: process.env.PAYLOAD_CLOUD_BUCKET_REGION,
})
await refreshSession()

return {
identityID,
Expand Down
46 changes: 46 additions & 0 deletions packages/payload-cloud/src/utilities/refreshSession.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import type { CognitoUserSession } from 'amazon-cognito-identity-js'

import { CognitoIdentityClient } from '@aws-sdk/client-cognito-identity'
import * as AWS from '@aws-sdk/client-s3'
import { fromCognitoIdentityPool } from '@aws-sdk/credential-providers'

import { authAsCognitoUser } from './authAsCognitoUser.js'

export type GetStorageClient = () => Promise<{
identityID: string
storageClient: AWS.S3
}>

export let storageClient: AWS.S3 | null = null
export let session: CognitoUserSession | null = null
export let identityID: string

export const refreshSession = async () => {
session = await authAsCognitoUser(
process.env.PAYLOAD_CLOUD_PROJECT_ID,
process.env.PAYLOAD_CLOUD_COGNITO_PASSWORD,
)

const cognitoIdentity = new CognitoIdentityClient({
credentials: fromCognitoIdentityPool({
clientConfig: {
region: 'us-east-1',
},
identityPoolId: process.env.PAYLOAD_CLOUD_COGNITO_IDENTITY_POOL_ID,
logins: {
[`cognito-idp.us-east-1.amazonaws.com/${process.env.PAYLOAD_CLOUD_COGNITO_USER_POOL_ID}`]:
session.getIdToken().getJwtToken(),
},
}),
})

const credentials = await cognitoIdentity.config.credentials()

// @ts-expect-error - Incorrect AWS types
identityID = credentials.identityId

storageClient = new AWS.S3({
credentials,
region: process.env.PAYLOAD_CLOUD_BUCKET_REGION,
})
}