Skip to content

Commit

Permalink
fix: some errant re-names in the token vending machine stack
Browse files Browse the repository at this point in the history
  • Loading branch information
cprice404 committed Sep 14, 2023
1 parent 0cad782 commit a0d8bed
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 39 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import {
ExpiresIn,
AllTopics,
CacheRole,
TopicRole,
type DisposableTokenScope,
} from "@gomomento/sdk";
import {ExpiresIn, AllTopics, CacheRole, TopicRole, DisposableTokenScope} from '@gomomento/sdk';

/**
* First, set the scope of permissions for your tokens.
Expand Down Expand Up @@ -49,14 +43,15 @@ export const tokenPermissions: DisposableTokenScope = {
permissions: [
{
role: CacheRole.ReadWrite,
cache: "default-cache"
cache: 'default-cache',
},
{
role: TopicRole.PublishSubscribe,
cache: "default-cache",
topic: AllTopics
}
]};
role: TopicRole.PublishSubscribe,
cache: 'default-cache',
topic: AllTopics,
},
],
};

/**
* Second, set the TTL for your tokens in terms of seconds, minutes, hours,
Expand All @@ -68,15 +63,15 @@ export const tokenPermissions: DisposableTokenScope = {
export const tokenExpiresIn: ExpiresIn = ExpiresIn.hours(1);

/**
* Third, set the authentication method for the token vending machine to protect
* Third, set the authentication method for the token vending machine to protect
* against unauthorized users. The available options are provided below.
*
*
* Note: when using Amazon Cognito, you'll need to first sign into Cognito to get an ID
* token that you'll include in your requests to the Token Vending Machine API.
* token that you'll include in your requests to the Token Vending Machine API.
*/
export enum AuthenticationMethod {
Open, // no authentication
Open, // no authentication
LambdaAuthorizer, // use Lambda Authorizer attached to API Gateway
AmazonCognito, // use Cognito user pool authorizer attached to API Gateway
AmazonCognito, // use Cognito user pool authorizer attached to API Gateway
}
export const authenticationMethod: AuthenticationMethod = AuthenticationMethod.Open;
export const authenticationMethod: AuthenticationMethod = AuthenticationMethod.Open;
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayPr
if (vendorApiKeySecretName === undefined) {
throw new Error("Missing required env var 'MOMENTO_API_KEY_SECRET_NAME");
}
console.log("headers in handler:", event.headers);
const vendedApiKey = await vendApiKey(vendorApiKeySecretName, event.headers);
console.log('headers in handler:', event.headers);
const vendedApiKey = await vendDisposableToken(vendorApiKeySecretName, event.headers);
return {
statusCode: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify(vendedApiKey),
};
Expand All @@ -34,26 +34,31 @@ export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayPr
}
};

interface VendedApiKey {
apiKey: string;
interface VendedToken {
authToken: string;
expiresAt: number;
}

async function vendApiKey(vendorApiKeySecretName: string, headers: APIGatewayProxyEventHeaders): Promise<VendedApiKey> {
async function vendDisposableToken(
vendorApiKeySecretName: string,
headers: APIGatewayProxyEventHeaders
): Promise<VendedToken> {
const momentoAuthClient = await getMomentoAuthClient(vendorApiKeySecretName);

let generateTokenResponse;
if (authenticationMethod === AuthenticationMethod.AmazonCognito) {
const cognitoUserTokenPermissions = determineCognitoUserTokenScope(headers);
generateTokenResponse = await momentoAuthClient.generateDisposableToken(cognitoUserTokenPermissions, tokenExpiresIn);
}
else {
generateTokenResponse = await momentoAuthClient.generateDisposableToken(
cognitoUserTokenPermissions,
tokenExpiresIn
);
} else {
generateTokenResponse = await momentoAuthClient.generateDisposableToken(tokenPermissions, tokenExpiresIn);
}

if (generateTokenResponse instanceof GenerateDisposableToken.Success) {
return {
apiKey: generateTokenResponse.apiKey,
authToken: generateTokenResponse.authToken,
expiresAt: generateTokenResponse.expiresAt.epoch(),
};
} else {
Expand All @@ -62,18 +67,16 @@ async function vendApiKey(vendorApiKeySecretName: string, headers: APIGatewayPro
}

function determineCognitoUserTokenScope(headers: APIGatewayProxyEventHeaders) {
if (!("cachename" in headers) || !("usergroup" in headers)) {
if (!('cachename' in headers) || !('usergroup' in headers)) {
throw new Error("Could not find expected headers 'cachename' and 'usergroup'");
}

if (headers["cachename"] && headers["usergroup"] === 'ReadWriteUserGroup') {
return TokenScopes.topicPublishSubscribe(headers["cachename"], AllTopics);
}
else if (headers["cachename"] && headers["usergroup"] === 'ReadOnlyUserGroup') {
return TokenScopes.topicSubscribeOnly(headers["cachename"], AllTopics);
}
else {
throw new Error(`Unrecognized Cognito user group: ${headers["usergroup"]}`);
if (headers['cachename'] && headers['usergroup'] === 'ReadWriteUserGroup') {
return TokenScopes.topicPublishSubscribe(headers['cachename'], AllTopics);
} else if (headers['cachename'] && headers['usergroup'] === 'ReadOnlyUserGroup') {
return TokenScopes.topicSubscribeOnly(headers['cachename'], AllTopics);
} else {
throw new Error(`Unrecognized Cognito user group: ${headers['usergroup']}`);
}
}

Expand Down

0 comments on commit a0d8bed

Please sign in to comment.