def append_session_headers(self, account, headers):
     if account:
         userURL = str(account.get_value(CE+'user'))
         displayName = account.get_value(FOAF+'nick', userURL, "")
         if not displayName or displayName == "":
             displayName = account.get_value(FOAF+'givenName', userURL, "")
             if not displayName or displayName == "":
                 displayName = account.get_value(CE+'account_id')
         fkaURL = utils.get_claims(self.environ)['user']
         claims = { # normal RDF_JSON turns out to be too voluminous. Make something small
             'exp': time.time() + 3600,
             'user': userURL,
             'acc': account.graph_url, #TODO remove this
             'disp': displayName,
             'fka': fkaURL }
     else:
         claims = utils.create_anonymous_user_claims(self.environ)
     sessionId = cryptography.encode_jwt(claims) 
     cookie = Cookie.SimpleCookie()
     cookie['SSSESSIONID'] = sessionId # SSSESSIONID  is 'Site Server Session ID'
     cookie['SSSESSIONID']['path'] = '/'
     cookie['user'] = claims['user']
     cookie['user']['path'] = '/'
     cookie_headers = map(lambda morsel: ('Set-Cookie', morsel.OutputString()), cookie.values())
     headers.extend(cookie_headers)
     return headers
Beispiel #2
0
def handler(event, context):
    # Get auth params
    claims = event["requestContext"]["authorizer"]["jwt"]["claims"]
    email, _, _, is_superuser = get_claims(claims=claims)

    # Get route params
    stackset_id = event["pathParameters"]["id"]

    # Read env data
    state_table = os.environ["dynamodb_state_table_name"]
    cleanup_sfn_arn = os.environ["cleanup_sfn_arn"]

    # Check if the requester owns the stackset
    stackset_data = get_stackset_state_data(stackset_id=stackset_id, table_name=state_table)
    if not stackset_data or (stackset_data["email"] != email and not is_superuser):
        return {
            "statusCode": 400,
            "body": json.dumps({"message": "You're not authorized to modify this instance."}),
            "headers": {"Content-Type": "application/json"},
        }

    # Deprovision stackset
    owner_email = stackset_data["email"]
    response = initiate_stackset_deprovisioning(
        stackset_id=stackset_id,
        cleanup_sfn_arn=cleanup_sfn_arn,
        owner_email=owner_email,
    )
    logger.info(f"SFN cleanup execution response: {response}")

    return {}
def handler(event, context):
    claims = event["requestContext"]["authorizer"]["jwt"]["claims"]
    email, _, _, is_superuser = get_claims(claims=claims)

    # read in data from request path
    stackset_id = event["pathParameters"]["id"]

    # read in data from environment
    state_table = os.environ["dynamodb_state_table_name"]

    # get details of the specified stackset
    stackset_data = get_stackset_state_data(stackset_id=stackset_id,
                                            table_name=state_table)
    if not stackset_data or (stackset_data["email"] != email
                             and not is_superuser):
        return {
            "statusCode":
            400,
            "body":
            json.dumps(
                {"message": "You're not authorized to modify this instance."}),
            "headers": {
                "Content-Type": "application/json"
            },
        }

    instances = get_instance_details(stacksets=[stackset_data])

    client = boto3.client("ec2", region_name=instances[0]["region"])
    client.start_instances(InstanceIds=[instances[0]["instance_id"]])

    return {}
def handler(event, context):
    claims = event["requestContext"]["authorizer"]["jwt"]["claims"]
    email, group, _, is_superuser = get_claims(claims=claims)

    # read in data from request path
    stackset_id = event["pathParameters"]["id"]

    # read in data from environment
    state_table = os.environ["dynamodb_state_table_name"]
    permissions_table = os.environ["dynamodb_permissions_table_name"]

    # get details of the specified stackset
    stackset_data = get_stackset_state_data(stackset_id=stackset_id,
                                            table_name=state_table)
    if not stackset_data or (stackset_data["email"] != email
                             and not is_superuser):
        raise UnauthorizedForInstanceError()

    # get user group permissions
    permissions = get_permissions_for_group(table_name=permissions_table,
                                            group_name=group)
    max_extension_count = permissions["max_extension_count"]

    # check user hasn't exceeded the max number of extensions
    if not is_superuser and stackset_data[
            "extension_count"] >= max_extension_count:
        raise InstanceUpdateError(
            f"You cannot extend instance lifetime more than {stackset_data['extension_count']} times."
        )

    new_expiry = stackset_data["expiry"] + timedelta(days=1)
    new_extension_count = stackset_data["extension_count"] + 1

    client = boto3.client("dynamodb")
    client.update_item(
        TableName=state_table,
        Key={"stacksetID": {
            "S": stackset_id
        }},
        UpdateExpression=
        "SET extensionCount = :extensionCount, expiry = :expiry",
        ExpressionAttributeValues={
            ":extensionCount": {
                "N": str(new_extension_count)
            },
            ":expiry": {
                "S": new_expiry.isoformat()
            },
        },
    )

    return {
        "stackset_id": stackset_id,
        "can_extend": is_superuser
        or new_extension_count < max_extension_count,
        "expiry": new_expiry.isoformat(),
    }
Beispiel #5
0
def handler(event, context):
    claims = event["requestContext"]["authorizer"]["jwt"]["claims"]
    _, group, *rest = get_claims(claims=claims)

    # read in data from environment
    permissions_table = os.environ["dynamodb_permissions_table_name"]

    # Get config from dynamodb
    permissions = get_permissions_for_group(table_name=permissions_table, group_name=group)

    # Restructure the permissions
    del permissions["operating_systems"]

    return permissions
Beispiel #6
0
def send_auth_challenge(environ, start_response, best_match_content_type='application/rdf+json+ce'):
    claims = utils.get_claims(environ)
    if claims is not None and 'acc' in claims:
        start_response('403 Forbidden', [])
        return ['access forbidden']
    else:
        original_url = '%s%s' % (environ['PATH_INFO'], '?%s'%environ['QUERY_STRING'] if environ['QUERY_STRING'] else '')
        if best_match_content_type == 'text/html':
            response_body = '<html><header><script>window.name = "%s";window.location.href = "/account/login"</script></header></html>' % original_url
        else:
            response_body = '{"http://ibm.com/ce/ns#login-page": "/account/login"}'
        response_headers = [('WWW-Authenticate', 'x-signature-auth realm=%s' % environ['SERVER_NAME']),('Content-Type', best_match_content_type), ('Content-Length', str(len(response_body)))]
        origin = environ.get('HTTP_ORIGIN')
        if origin:
            response_headers.append(('Access-Control-Allow-Origin', origin))
            response_headers.append(('Access-Control-Allow-Credentials', 'true'))
            response_headers.append(('Access-Control-Expose-Headers', 'Content-Location'))
        start_response('401 Unauthorized', response_headers)
        return [response_body]
Beispiel #7
0
def handler(event, context):
    claims = event["requestContext"]["authorizer"]["jwt"]["claims"]
    email, group, _, is_superuser = get_claims(claims=claims)

    # read in data from environment
    state_table = os.environ["dynamodb_state_table_name"]
    permissions_table = os.environ["dynamodb_permissions_table_name"]

    # Get config from dynamodb
    stacksets = get_owned_stacksets(table_name=state_table,
                                    email=email,
                                    is_superuser=is_superuser)
    permissions = get_permissions_for_group(table_name=permissions_table,
                                            group_name=group)
    max_extension_count = permissions["max_extension_count"]
    instances = get_instance_details(
        stacksets=stacksets,
        max_extension_count=max_extension_count,
        is_superuser=is_superuser,
    )

    return instances
Beispiel #8
0
def handler(event, context):
    claims = event["requestContext"]["authorizer"]["jwt"]["claims"]
    email, group, _, is_superuser = get_claims(claims=claims)

    # read in data from request path
    stackset_id = event["pathParameters"]["id"]

    # Get body params
    payload = json.loads(event["body"])

    # read in data from environment
    state_table = os.environ["dynamodb_state_table_name"]
    permissions_table = os.environ["dynamodb_permissions_table_name"]

    # get details of the specified stackset
    stackset_data = get_stackset_state_data(stackset_id=stackset_id,
                                            table_name=state_table)
    if not stackset_data or (stackset_data["email"] != email
                             and not is_superuser):
        raise UnauthorizedForInstanceError()

    # Get params the user has permissions for and sanitize input
    permissions = get_permissions_for_group(table_name=permissions_table,
                                            group_name=group)
    serializer = get_request_serializer(
        instance_types=permissions["instance_types"], )

    try:
        data = serializer.load(payload)
    except ValidationError as e:
        raise InvalidArgumentsError(message=str(e))

    instance_type = data["instance_type"]
    update_stackset(stackset_id=stackset_id, InstanceType=instance_type)

    return {}
Beispiel #9
0
def debug():
    return_val = "JWT claims:\n"
    return_val += get_claims(request.headers['jwt'])
    return return_val
Beispiel #10
0
def handler(event, context):
    # Get auth params
    claims = event["requestContext"]["authorizer"]["jwt"]["claims"]
    email, group, username, is_superuser = get_claims(claims=claims)

    # Get body params
    payload = json.loads(event["body"])

    # Read env data
    provision_sfn_arn = os.environ["provision_sfn_arn"]
    permissions_table = os.environ["dynamodb_permissions_table_name"]
    state_table = os.environ["dynamodb_state_table_name"]

    # Get params the user has permissions for
    permissions = get_permissions_for_group(table_name=permissions_table, group_name=group)

    # Validate the user provided params, raises a ValidationException if user has no permissions
    current_account_id = get_account_id()
    serializer = get_request_serializer(
        current_account_id=current_account_id,
        regions=permissions["region_map"].keys(),
        instance_types=permissions["instance_types"],
        operating_systems=permissions["region_map"].get(payload.get("region"), []),
        max_days_to_expiry=permissions["max_days_to_expiry"],
        is_superuser=is_superuser,
    )
    try:
        data = serializer.load(payload)
    except ValidationError as e:
        return {
            "statusCode": 400,
            "body": json.dumps({"message": e.messages}),
            "headers": {"Content-Type": "application/json"},
        }

    # Check if instance count is within limits if the user isn't a superuser
    if is_superuser:
        stack_email = data.pop("email")
        stack_username = data.pop("username")
    else:
        stack_email = email
        stack_username = username

        stacksets = get_owned_stacksets(table_name=state_table, email=stack_email)
        if len(stacksets) >= permissions["max_instance_count"]:
            return {
                "statusCode": 400,
                "body": json.dumps(
                    {"message": f"Instance limit exceeded. You already own {len(stacksets)} instances."}
                ),
                "headers": {"Content-Type": "application/json"},
            }

    # Provision stackset
    sfn_execution_arn = provision_stackset(
        provision_sfn_arn=provision_sfn_arn,
        email=stack_email,
        group=group,
        username=stack_username,
        user=claims,
        **data,
    )

    return {
        "sfn_execution_arn": sfn_execution_arn,
        "email": stack_email,
        "username": stack_username,
    }