All files / lib/lambda postAuth.ts

95.52% Statements 64/67
67.56% Branches 25/37
100% Functions 8/8
95.38% Lines 62/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173                    1x     1x   6x 1x   5x 1x     4x   4x 4x   1x 1x     3x 3x 3x 1x   2x   2x 2x 2x             2x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x             1x                           1x 1x 1x   1x     3x       1x   1x       1x     6x   1x     5x   1x     1x             1x 1x 1x   1x   1x             1x                     1x 1x 2x   1x   1x     1x                     1x 1x 1x          
import { Handler } from "aws-lambda";
import { UserRoles, STATE_ROLES } from "shared-types";
import {
  CognitoIdentityProviderClient,
  AdminUpdateUserAttributesCommand,
  AdminGetUserCommand,
} from "@aws-sdk/client-cognito-identity-provider";
import { getSecret } from "shared-utils";
 
// Initialize Cognito client
const client = new CognitoIdentityProviderClient({
  region: process.env.region || process.env.REGION_A || "us-east-1",
});
export const handler: Handler = async (event) => {
  // Check if idmInfoSecretArn is provided
  if (!process.env.idmAuthzApiKeyArn) {
    throw "ERROR: process.env.idmAuthzApiKeyArn is required";
  }
  if (!process.env.idmAuthzApiEndpoint) {
    throw "ERROR: process.env.idmAuthzApiEndpoint is required";
  }
 
  const apiEndpoint: string = process.env.idmAuthzApiEndpoint;
  let apiKey: string;
  try {
    apiKey = await getSecret(process.env.idmAuthzApiKeyArn);
  } catch (error) {
    console.error("Error retrieving secret from Secrets Manager:", error);
    throw error;
  }
 
  const { request } = event;
  const { userAttributes } = request;
  if (!userAttributes.identities) {
    console.log("User is not managed externally. Nothing to do.");
  } else {
    console.log("Getting user attributes from external API");
 
    try {
      const username = userAttributes["custom:username"]; // This is the four-letter IDM username
      const response = await fetch(`${apiEndpoint}/api/v1/authz/id/all?userId=${username}`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          "x-api-key": apiKey,
        },
      });
      if (!response.ok) {
        throw new Error(
          `Network response was not ok. Response was ${response.status}: ${response.statusText}`,
        );
      }
      const data = await response.json();
      console.log(JSON.stringify(data, null, 2));
      const roleArray: string[] = [];
      const stateArray: string[] = [];
      data.userProfileAppRoles.userRolesInfoList.forEach((element: any) => {
        const role = element.roleName;
        Eif (Object.values(UserRoles).includes(role)) {
          roleArray.push(role);
          Eif (STATE_ROLES.includes(role)) {
            element.roleAttributes.forEach((attr: any) => {
              Eif (attr.name === "State/Territory") {
                stateArray.push(attr.value);
              }
            });
          }
        }
      });
 
      const attributeData: any = {
        Username: event.userName,
        UserPoolId: event.userPoolId,
        UserAttributes: [
          {
            Name: "custom:cms-roles",
            Value: roleArray.join(),
          },
          {
            Name: "custom:state",
            Value: stateArray.join(),
          },
        ],
      };
      console.log("Putting user attributes as: ");
      console.log(JSON.stringify(attributeData, null, 2));
      await updateUserAttributes(attributeData);
    } catch (error) {
      console.error("Error performing post auth:", error);
    }
  }
  return event;
};
 
async function updateUserAttributes(params: any): Promise<void> {
  try {
    // Fetch existing user attributes
    const getUserCommand = new AdminGetUserCommand({
      UserPoolId: params.UserPoolId,
      Username: params.Username,
    });
    const user = await client.send(getUserCommand);
 
    // Check for existing "custom:cms-roles"
    const cmsRolesAttribute = user.UserAttributes?.find((attr) => attr.Name === "custom:cms-roles");
    const existingRoles =
      cmsRolesAttribute && cmsRolesAttribute.Value ? cmsRolesAttribute.Value.split(",") : [];
 
    // Check for existing "custom:state"
    const stateAttribute = user.UserAttributes?.find((attr) => attr.Name === "custom:state");
    const existingStates =
      stateAttribute && stateAttribute.Value ? stateAttribute.Value.split(",") : [];
 
    // Prepare for updating user attributes
    const attributeData: any = {
      UserPoolId: params.UserPoolId,
      Username: params.Username,
      UserAttributes: params.UserAttributes,
    };
 
    // Ensure "onemac-micro-super" is preserved
    Eif (existingRoles.includes("onemac-micro-super")) {
      const rolesIndex = attributeData.UserAttributes.findIndex(
        (attr: any) => attr.Name === "custom:cms-roles",
      );
      if (rolesIndex !== -1) {
        // Only merge if new roles are not empty
        const newRoles = attributeData.UserAttributes[rolesIndex].Value
          ? new Set(
              attributeData.UserAttributes[rolesIndex].Value.split(",").concat(
                "onemac-micro-super",
              ),
            )
          : new Set(["onemac-micro-super"]); // Ensure "onemac-micro-super" is always included
        attributeData.UserAttributes[rolesIndex].Value = Array.from(newRoles).join(",");
      } else E{
        // Add "custom:cms-roles" with "onemac-micro-super"
        attributeData.UserAttributes.push({
          Name: "custom:cms-roles",
          Value: "onemac-micro-super",
        });
      }
    }
 
    // Ensure "ZZ" state is preserved
    Eif (existingStates.includes("ZZ")) {
      const stateIndex = attributeData.UserAttributes.findIndex(
        (attr: any) => attr.Name === "custom:state",
      );
      if (stateIndex !== -1) {
        // Only merge if new states are not empty
        const newStates = attributeData.UserAttributes[stateIndex].Value
          ? new Set(attributeData.UserAttributes[stateIndex].Value.split(",").concat("ZZ"))
          : new Set(["ZZ"]); // Ensure "ZZ" is always included
        attributeData.UserAttributes[stateIndex].Value = Array.from(newStates).join(",");
      } else E{
        // Add "custom:state" with "ZZ"
        attributeData.UserAttributes.push({
          Name: "custom:state",
          Value: "ZZ",
        });
      }
    }
 
    // Update the user's attributes
    const updateCommand = new AdminUpdateUserAttributesCommand(attributeData);
    await client.send(updateCommand);
    console.log(`Attributes for user ${params.Username} updated successfully.`);
  } catch (error) {
    console.error("Error updating user's attributes:", error);
  }
}