public record IamRole()

in sources/src/main/java/com/google/solutions/jitaccess/auth/IamRole.java [30:100]


public record IamRole(
  @NotNull String name
) {
  private static final String PREDEFINED_ROLE_PREFIX = "roles/";
  private static final String CUSTOM_ORG_ROLE_PREFIX = "organizations/";
  private static final String CUSTOM_PROJECT_ROLE_PREFIX = "projects/";

  public IamRole {
    Preconditions.checkArgument(
      name.startsWith(PREDEFINED_ROLE_PREFIX) ||
        name.startsWith(CUSTOM_ORG_ROLE_PREFIX) ||
        name.startsWith(CUSTOM_PROJECT_ROLE_PREFIX),
      "The IAM role uses an invalid prefix");
  }

  /**
   * Parse a role that uses one of the following formats:
   * <p>
   * - roles/... (predefined)
   * - projects/... (custom project role)
   * - organizations/... (custom organization role)
   *
   * @return empty if the input string is malformed.
   */
  public static @NotNull Optional<IamRole> parse(@Nullable String s) {
    if (s == null) {
      return Optional.empty();
    }

    s = s.trim();

    if (s.startsWith(PREDEFINED_ROLE_PREFIX) && s.length() > PREDEFINED_ROLE_PREFIX.length()) {
      return Optional.of(new IamRole(s));
    }
    else if (s.startsWith(CUSTOM_ORG_ROLE_PREFIX) && s.length() > CUSTOM_ORG_ROLE_PREFIX.length()) {
      return Optional.of(new IamRole(s));
    }
    else if (s.startsWith(CUSTOM_PROJECT_ROLE_PREFIX) && s.length() > CUSTOM_PROJECT_ROLE_PREFIX.length()) {
      return Optional.of(new IamRole(s));
    }
    else {
      return Optional.empty();
    }
  }

  @Override
  public String toString() {
    return this.name;
  }

  /**
   * Check if this is a predefined role.
   */
  public boolean isPredefined() {
    return this.name.startsWith(PREDEFINED_ROLE_PREFIX);
  }

  /**
   * Check if this is a custom project role.
   */
  public boolean isCustomProjectRole() {
    return this.name.startsWith(CUSTOM_PROJECT_ROLE_PREFIX);
  }

  /**
   * Check if this is a custom organization role.
   */
  public boolean isCustomOrganizationRole() {
    return this.name.startsWith(CUSTOM_ORG_ROLE_PREFIX);
  }
}