Example #1
0
def any_access():
    """
    Check if the user is in our database

    :note if a user is specified with empty access it still counts

    :query project: (optional) Check for read access to a specific program/project

    """
    project = flask.request.args.get("project")
    projects = None
    if flask.g.token is None:
        flask.g.user = current_session.merge(flask.g.user)
        projects = flask.g.user.project_access
    else:
        projects = flask.g.token["context"]["user"]["projects"]

    success = False

    if not project and len(projects) > 0:
        success = True
    elif project and project in projects:
        access = projects[project]
        if "read" in access:
            success = True

    if success:
        resp = flask.make_response(flask.jsonify({"result": "success"}), 200)
        resp.headers["REMOTE_USER"] = flask.g.user.username
        return resp
    raise Unauthorized("Please login")
Example #2
0
 def set_acls(self):
     if "acl" in self.index_document:
         return set(self.index_document["acl"])
     elif "acls" in self.metadata:
         return set(self.metadata["acls"].split(","))
     else:
         raise Unauthorized("This file is not accessible")
Example #3
0
 def get_signed_url(
     self,
     protocol,
     action,
     expires_in,
     force_signed_url=True,
     r_pays_project=None,
     file_name=None,
 ):
     if self.public and action == "upload":
         raise Unauthorized("Cannot upload on public files")
     # don't check the authorization if the file is public
     # (downloading public files with no auth is fine)
     if not self.public and not self.check_authorization(action):
         raise Unauthorized(
             "You don't have access permission on this file: {}".format(
                 self.file_id))
     if action is not None and action not in SUPPORTED_ACTIONS:
         raise NotSupported("action {} is not supported".format(action))
     return self._get_signed_url(protocol, action, expires_in,
                                 force_signed_url, r_pays_project,
                                 file_name)
Example #4
0
 def check_auth(self, provider, user):
     """
     check if the user should be authorized to storage resources
     """
     storage_access = any([
         "read-storage" in item
         for item in list(user.project_access.values())
     ])
     backend_access = any([
         sa.provider.name == provider for p in list(user.projects.values())
         for sa in p.storage_access
     ])
     if storage_access and backend_access:
         return True
     else:
         raise Unauthorized("Your are not authorized")
Example #5
0
def create_user_access_token(keypair, api_key, expires_in):
    """
    create access token given a user's api key
    Args:
        keypair: RSA keypair for signing jwt
        api_key: user created jwt token, the azp should match with user.id
        expires_in: expiration time in seconds
    Return:
        access token
    """
    try:
        claims = validate_jwt(api_key, aud={"amanuensis"}, purpose="api_key")
        scopes = claims["aud"]
        user = get_user_from_claims(claims)
    except Exception as e:
        raise Unauthorized(str(e))
    return token.generate_signed_access_token(keypair.kid, keypair.private_key,
                                              user, expires_in, scopes).token
Example #6
0
    def get_credential_to_access_bucket(cls,
                                        bucket_name,
                                        aws_creds,
                                        expires_in,
                                        boto=None):
        s3_buckets = get_value(config, "S3_BUCKETS",
                               InternalError("buckets not configured"))
        if len(aws_creds) == 0 and len(s3_buckets) == 0:
            raise InternalError("no bucket is configured")
        if len(aws_creds) == 0 and len(s3_buckets) > 0:
            raise InternalError("credential for buckets is not configured")

        bucket_cred = s3_buckets.get(bucket_name)
        if bucket_cred is None:
            raise Unauthorized("permission denied for bucket")

        cred_key = get_value(
            bucket_cred, "cred",
            InternalError("credential of that bucket is missing"))

        # this is a special case to support public buckets where we do *not* want to
        # try signing at all
        if cred_key == "*":
            return {"aws_access_key_id": "*"}

        if "role-arn" not in bucket_cred:
            return get_value(
                aws_creds,
                cred_key,
                InternalError("aws credential of that bucket is not found"),
            )
        else:
            aws_creds_config = get_value(
                aws_creds,
                cred_key,
                InternalError("aws credential of that bucket is not found"),
            )
            return S3IndexedFileLocation.assume_role(bucket_cred, expires_in,
                                                     aws_creds_config, boto)
Example #7
0
def _force_update_user_google_account(
    user_id, google_email, proxy_group_id, _allow_new=False, requested_expires_in=None
):
    """
    Adds user's google account to proxy group and/or updates expiration for
    that google account's access.

    WARNING: This assumes that provided arguments represent valid information.
             This BLINDLY adds without verification. Do verification
             before this.

    Specifically, this ASSUMES that the proxy group provided belongs to the
    given user and that the user has ALREADY authenticated to prove the
    provided google_email is also their's.

    Args:
        user_id (str): User's identifier
        google_email (str): User's Google email
        proxy_group_id (str): User's Proxy Google group id
        _allow_new (bool, optional): Whether or not a new linkage between
            Google email and the given user should be allowed
        requested_expires_in (int, optional): Requested time (in seconds)
            during which the link will be valid

    Raises:
        NotFound: Linked Google account not found
        Unauthorized: Couldn't determine user

    Returns:
        Expiration time of the newly updated google account's access
    """
    user_google_account = (
        current_session.query(UserGoogleAccount)
        .filter(UserGoogleAccount.email == google_email)
        .first()
    )

    if not user_google_account:
        if _allow_new:
            if user_id is not None:
                user_google_account = add_new_user_google_account(
                    user_id, google_email, current_session
                )
                logger.info(
                    "Linking Google account {} to user with id {}.".format(
                        google_email, user_id
                    )
                )
            else:
                raise Unauthorized(
                    "Could not determine authed user "
                    "from session. Unable to link Google account."
                )
        else:
            raise NotFound(
                "User does not have a linked Google account. Update "
                "was attempted and failed."
            )

    # timestamp at which the link will expire
    expiration = get_default_google_account_expiration()
    if requested_expires_in:
        requested_expiration = int(time.time()) + requested_expires_in
        expiration = min(requested_expiration, expiration)

    force_update_user_google_account_expiration(
        user_google_account, proxy_group_id, google_email, expiration, current_session
    )

    logger.info(
        "Adding user's (id: {}) Google account to their proxy group (id: {})."
        " Expiration: {}".format(
            user_google_account.user_id, proxy_group_id, expiration
        )
    )

    current_session.commit()

    return expiration