示例#1
0
def get_session_status(account_id, user_id, session_id):
    if session_id is None:
        raise SessionManagerException(
            "Destroy action must include a sessionId")
    d = dynamo_sessions.lookup(account_id,
                               user_id=user_id,
                               session_id=session_id)
    if len(d) > 0:
        return {"success": True, "session": d[0]}
    else:
        return {"success": True, "session": None}
示例#2
0
def renew_session(account_id, user_id, session_id):
    m = dynamo_sessions.lookup(account_id,
                               user_id=user_id,
                               session_id=session_id)
    if len(m) == 0:
        return {"success": False, "message": "Session has expired"}
    m = m[0]
    c = get_cognito_client()
    cred_d = get_credentials(c, m['identityId'])
    m.update(cred_d)
    dynamo_sessions.create(m)
    LOGGER.info("renewed session for account_id={0}, session_id={1}".format(
        account_id, session_id))
    return {"success": True, "session": m}
示例#3
0
def destroy_session(account_id, user_id, session_id):
    d = dynamo_sessions.lookup(account_id,
                               user_id=user_id,
                               session_id=session_id)
    if len(d) > 0:
        sqs_url = d[0]['sqsUrl']
        c = boto3.client('sqs')
        try:
            c.delete_queue(QueueUrl=sqs_url)
            LOGGER.info("Removed queue {0}".format(sqs_url))
        except:
            LOGGER.warn("Unable to remove queue {0}".format(sqs_url))
        LOGGER.info("Destroying session {0}, user {1}".format(
            session_id, user_id))
        dynamo_sessions.destroy(account_id, user_id, session_id)
        return {"success": True}
    else:
        return {"success": False, "message": "session not found"}
示例#4
0
def create_sqs_queue(account_id,
                     user_id,
                     session_id,
                     restrict_ip=None,
                     msg_retention_period=None):
    if msg_retention_period is None:
        msg_retention_period = str(
            int(os.getenv('SQS_MESSAGE_RETENTION_PERIOD')))
    else:
        msg_retention_period = str(int(msg_retention_period))
    # first lookup to see if we already have for this session
    d = dynamo_sessions.lookup(account_id,
                               user_id=user_id,
                               session_id=session_id,
                               max_expired_age=86400)
    cog_c = get_cognito_client()
    if len(d) >= 1:
        LOGGER.info("Session {0} already exists, reusing".format(session_id))
        # if credentials expire in less than an hour, then renew
        session = d[0]
        if int(session['expires']) - int(time.time()) < 3600:
            # renew
            creds = get_credentials(cog_c, session['identityId'])
            session.update(creds)
        return session
    sqs_c = boto3.client('sqs')
    pool_id = get_identity_pool()
    r = cog_c.get_id(IdentityPoolId=pool_id)
    cog_id = r['IdentityId']
    cred_d = get_credentials(cog_c, cog_id)
    if restrict_ip is not None:
        policy = {
            'Version':
            '2012-10-17',
            'Statement': [{
                'Effect':
                "Allow",
                'Action': ["sqs:ReceiveMessage", "sqs:GetQueueAttributes"],
                'Condition': {
                    'IpAddress': {
                        "aws:SourceIp": restrict_ip
                    }
                },
                'Resource':
                "*"
            }]
        }
    else:
        policy = None
    # use hash to generate queue name based on account, session
    # this ensures it is well-distributed, which will be useful when
    # we need to scroll through a large number of queues

    # also encode creation time / 10000, to roughly determine age
    # useful later for cleanup
    with open('/dev/urandom', 'rb') as f_rand:
        aes_key = f_rand.read(32)
        queue_rand = f_rand.read(32)

    queue_name = os.getenv('SQS_QUEUE_PREFIX') + '-' + \
                 base64.urlsafe_b64encode(queue_rand).replace('=','')
    if len(queue_name) > 80:
        LOGGER.warn(
            "Queue name is too long, max 80 characters.  Trimming.  Try shortening the queue prefix."
        )
        queue_name = queue_name[:80]
    q_attr = {'MessageRetentionPeriod': msg_retention_period}
    if policy is not None:
        q_attr['Policy'] = json.dumps(policy)
    try:
        r = sqs_c.create_queue(QueueName=queue_name, Attributes=q_attr)
    except botocore.errorfactory.ClientError, err:
        if err.response['Error'][
                'Code'] == 'QueueAlreadyExists' and policy is not None:
            LOGGER.info("Queue {0} already exists, resetting policy".format(
                queue_name))
            r = sqs_c.get_queue_url(QueueName=queue_name)
            sqs_c.set_queue_attributes(
                QueueUrl=r['QueueUrl'],
                Attributes={'Policy': json.dumps(policy)})
        else:
            raise
def get_sessions_for_target(target):
    return dynamo_sessions.lookup(account_id=target[0],
                                  session_id=target[1],
                                  user_id=target[2],
                                  max_expired_age=86400)