Esempio n. 1
0
 def test_update_account(self):
     """ ACCOUNT (CORE): Test changing and quering account parameters """
     usr = account_name_generator()
     add_account(usr, 'USER', '*****@*****.**', 'root', **self.vo)
     assert get_account_info(usr, **self.vo)['status'] == AccountStatus.ACTIVE  # Should be active by default
     update_account(account=usr, key='status', value=AccountStatus.SUSPENDED, **self.vo)
     assert get_account_info(usr, **self.vo)['status'] == AccountStatus.SUSPENDED
     update_account(account=usr, key='status', value=AccountStatus.ACTIVE, **self.vo)
     assert get_account_info(usr, **self.vo)['status'] == AccountStatus.ACTIVE
     update_account(account=usr, key='email', value='test', **self.vo)
     email = get_account_info(account=usr, **self.vo)['email']
     assert email == 'test'
     del_account(usr, 'root', **self.vo)
Esempio n. 2
0
 def test_update_account(self):
     """ ACCOUNT (CORE): Test changing and quering account parameters """
     usr = account_name_generator()
     add_account(usr, 'USER', '*****@*****.**', 'root')
     assert_equal(get_account_info(usr)['status'], AccountStatus.ACTIVE)  # Should be active by default
     update_account(account=usr, key='status', value=AccountStatus.SUSPENDED)
     assert_equal(get_account_info(usr)['status'], AccountStatus.SUSPENDED)
     update_account(account=usr, key='status', value=AccountStatus.ACTIVE)
     assert_equal(get_account_info(usr)['status'], AccountStatus.ACTIVE)
     update_account(account=usr, key='email', value='test')
     email = get_account_info(account=usr)['email']
     assert_equal(email, 'test')
     del_account(usr, 'root')
Esempio n. 3
0
def select_account_name(identitystr, identity_type):
    """
    Looks for account corresponding to the provided identity.
    :param identitystr: identity string
    :param identity_type: identity_type e.g. x509, saml, oidc, userpass
    :returns: None or account string
    """
    accounts = identity.list_accounts_for_identity(identitystr, identity_type)
    ui_account = None
    if len(accounts) == 0:
        return None
    # check if ui_account param is set
    if 'ui_account' in input():
        ui_account = input()['ui_account']
    # if yes check if the accounts provided for users identity include this account
    if not ui_account and 'account' in input():
        ui_account = input()['account']
    if ui_account:
        if ui_account not in accounts:
            return None
        else:
            return ui_account
    else:
        # try to set the default account to the user account, if not available take the first account.
        def_account = accounts[0]
        for account in accounts:
            account_info = get_account_info(account)
            if account_info.account_type == AccountType.USER:
                def_account = account
                break
        selected_account = cookies().get('rucio-selected-account')
        if (selected_account):
            def_account = selected_account
        ui_account = def_account
    return ui_account
Esempio n. 4
0
    def get(self, account):
        """ get account parameters for given account name.

        .. :quickref: AccountParameter; Get account parameters.

        :param account: The account identifier.
        :status 200: OK.
        :status 401: Invalid auth token.
        :status 404: Account not found.
        :status 406: Not Acceptable.
        :returns: JSON dict containing informations about the requested user.
        """
        if account == 'whoami':
            # Redirect to the account uri
            frontend = request.headers.get('X-Requested-Host', default=None)
            if frontend:
                return redirect(f'{frontend}/accounts/{request.environ.get("issuer")}', code=302)
            return redirect(request.environ.get('issuer'), code=303)

        try:
            acc = get_account_info(account, vo=request.environ.get('vo'))
        except AccountNotFound as error:
            return generate_http_error_flask(404, error)
        except AccessDenied as error:
            return generate_http_error_flask(401, error)

        accdict = acc.to_dict()

        for key, value in accdict.items():
            if isinstance(value, datetime):
                accdict[key] = value.strftime('%Y-%m-%dT%H:%M:%S')

        del accdict['_sa_instance_state']

        return Response(render_json(**accdict), content_type="application/json")
Esempio n. 5
0
    def GET(self, account):
        """ get account information for given account name.

        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized
            404 Not Found
            500 InternalError

        :param Rucio-Account: Account identifier.
        :param Rucio-Auth-Token: as an 32 character hex string.

        :returns: JSON dict containing informations about the requested user.
        """
        header('Content-Type', 'application/json')
        if account == 'whoami':
            # Redirect to the account uri
            frontend = ctx.env.get('HTTP_X_REQUESTED_HOST')
            if frontend:
                raise redirect(frontend + "/accounts/%s" %
                               (ctx.env.get('issuer')))
            raise seeother(ctx.env.get('issuer'))

        acc = None
        try:
            acc = get_account_info(account)
        except AccountNotFound, e:
            raise generate_http_error(404, 'AccountNotFound', e.args[0][0])
Esempio n. 6
0
    def GET(self, account):
        """ get account information for given account name.

        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized
            404 Not Found
            500 InternalError

        :param Rucio-Account: Account identifier.
        :param Rucio-Auth-Token: as an 32 character hex string.

        :returns: JSON dict containing informations about the requested user.
        """
        header('Content-Type', 'application/json')
        if account == 'whoami':
            # Redirect to the account uri
            frontend = ctx.env.get('HTTP_X_REQUESTED_HOST')
            if frontend:
                raise redirect(frontend + "/accounts/%s" % (ctx.env.get('issuer')))
            raise seeother(ctx.env.get('issuer'))

        acc = None
        try:
            acc = get_account_info(account)
        except AccountNotFound, e:
            raise generate_http_error(404, 'AccountNotFound', e.args[0][0])
Esempio n. 7
0
    def test_api_account(self):
        """ ACCOUNT (API): Test external representation of account information """
        out = get_account_info(self.account_name, **self.vo)
        assert self.account_name == out['account']

        out = [acc['account'] for acc in list_accounts(**self.vo)]
        assert self.account_name in out
        if self.multi_vo:
            assert self.account.internal not in out
        assert '@' not in ' '.join(out)
Esempio n. 8
0
    def test_api_account(self):
        """ ACCOUNT (API): Test external representation of account information """
        out = get_account_info(self.account_name, **self.vo)
        assert_equal(self.account_name, out['account'])

        out = [acc['account'] for acc in list_accounts(**self.vo)]
        assert_in(self.account_name, out)
        if self.multi_vo:
            assert_not_in(self.account.internal, out)
        assert_not_in('@', ' '.join(out))
Esempio n. 9
0
def select_account_name(identitystr, identity_type, vo=None):
    """
    Looks for account (and VO if not known) corresponding to the provided identity.
    :param identitystr: identity string
    :param identity_type: identity_type e.g. x509, saml, oidc, userpass
    :returns: Tuple of None or account string, None or VO string or list of VO strings
    """
    ui_account = None
    if not MULTI_VO:
        vo = 'def'
    if vo is not None:
        accounts = identity.list_accounts_for_identity(identitystr,
                                                       identity_type)
    else:
        internal_accounts = identity_core.list_accounts_for_identity(
            identitystr, IdentityType.from_sym(identity_type))
        accounts = [account.external for account in internal_accounts]
        vos = [account.vo for account in internal_accounts]
        if vos:
            vos = list(set(vos))
            # If we only have 1 VO that matches the identity use that, otherwise return all possible VOs so the user can choose
            if len(vos) == 1:
                vo = vos[0]
            else:
                return None, vos

    if len(accounts) == 0:
        return None, vo
    # check if ui_account param is set
    if 'ui_account' in input():
        ui_account = input()['ui_account']
    # if yes check if the accounts provided for users identity include this account
    if not ui_account and 'account' in input():
        ui_account = input()['account']
    if ui_account:
        if ui_account not in accounts:
            return None, vo
        else:
            return ui_account, vo
    else:
        # try to set the default account to the user account, if not available take the first account.
        def_account = accounts[0]
        for account in accounts:
            account_info = get_account_info(account, vo=vo)
            if account_info.account_type == AccountType.USER:
                def_account = account
                break
        selected_account = cookies().get('rucio-selected-account')
        if (selected_account):
            def_account = selected_account
        ui_account = def_account
    return ui_account, vo
Esempio n. 10
0
    def GET(self, account):
        """ get account information for given account name.

        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized
            404 Not Found
            406 Not Acceptable
            500 InternalError

        :param Rucio-Account: Account identifier.
        :param Rucio-Auth-Token: as an 32 character hex string.

        :returns: JSON dict containing informations about the requested user.
        """
        header('Content-Type', 'application/json')
        if account == 'whoami':
            # Redirect to the account uri
            frontend = ctx.env.get('HTTP_X_REQUESTED_HOST')
            if frontend:
                raise redirect(frontend + "/accounts/%s" %
                               (ctx.env.get('issuer')))
            raise seeother(ctx.env.get('issuer'))

        acc = None
        try:
            acc = get_account_info(account, vo=ctx.env.get('vo'))
        except AccountNotFound as error:
            raise generate_http_error(404, 'AccountNotFound', error.args[0])
        except AccessDenied as error:
            raise generate_http_error(401, 'AccessDenied', error.args[0])
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__,
                                      error.args[0])
        except Exception as error:
            print(format_exc())
            raise InternalError(error)

        dict = acc.to_dict()

        for key, value in dict.items():
            if isinstance(value, datetime):
                dict[key] = value.strftime('%Y-%m-%dT%H:%M:%S')

        del dict['_sa_instance_state']

        return render_json(**dict)
Esempio n. 11
0
    def get(self, account):
        """ get account parameters for given account name.

        .. :quickref: AccountParameter; Get account parameters.

        :param account: The account identifier.
        :status 200: OK.
        :status 401: Invalid auth token.
        :status 404: Account not found.
        :status 406: Not Acceptable.
        :status 500: Database exception.
        :returns: JSON dict containing informations about the requested user.
        """
        if account == 'whoami':
            # Redirect to the account uri
            frontend = request.environ.get('HTTP_X_REQUESTED_HOST')
            if frontend:
                return redirect(frontend + "/accounts/%s" %
                                (request.environ.get('issuer')),
                                code=302)
            return redirect(request.environ.get('issuer'), code=303)

        acc = None
        try:
            acc = get_account_info(account)
        except AccountNotFound as error:
            return generate_http_error_flask(404, 'AccountNotFound',
                                             error.args[0])
        except AccessDenied as error:
            return generate_http_error_flask(401, 'AccessDenied',
                                             error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__,
                                             error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500

        dict = acc.to_dict()

        for key, value in dict.items():
            if isinstance(value, datetime):
                dict[key] = value.strftime('%Y-%m-%dT%H:%M:%S')

        del dict['_sa_instance_state']

        return Response(render_json(**dict), content_type="application/json")
Esempio n. 12
0
def check_token(rendered_tpl):
    attribs = None
    token = None
    js_token = ""
    js_account = ""
    def_account = None
    accounts = None
    cookie_accounts = None
    rucio_ui_version = version.version_string()

    ui_account = None
    if 'ui_account' in input():
        ui_account = input()['ui_account']

    render = template.render(join(dirname(__file__), '../templates'))
    if ctx.env.get('SSL_CLIENT_VERIFY') != 'SUCCESS':
        return render.problem(
            "No certificate provided. Please authenticate with a certificate registered in Rucio."
        )

    dn = ctx.env.get('SSL_CLIENT_S_DN')

    msg = "Your certificate (%s) is not mapped to any rucio account." % dn
    msg += "<br><br><font color=\"red\">First, please make sure it is correctly registered in <a href=\"https://voms2.cern.ch:8443/voms/atlas\">VOMS</a> and be patient until it has been fully propagated through the system.</font>"
    msg += "<br><br>Then, if it is still not working please contact <a href=\"mailto:[email protected]\">DDM Support</a>."

    # try to get and check the rucio session token from cookie
    session_token = cookies().get('x-rucio-auth-token')
    validate_token = authentication.validate_auth_token(session_token)

    # check if ui_account param is set and if yes, force new token
    if ui_account:
        accounts = identity.list_accounts_for_identity(dn, 'x509')

        if len(accounts) == 0:
            return render.problem(msg)

        if ui_account not in accounts:
            return render.problem(
                "The rucio account (%s) you selected is not mapped to your certificate (%s). Please select another account or none at all to automatically use your default account."
                % (ui_account, dn))

        cookie_accounts = accounts
        if (validate_token is None) or (validate_token['account'] !=
                                        ui_account):
            try:
                token = authentication.get_auth_token_x509(
                    ui_account, dn, 'webui', ctx.env.get('REMOTE_ADDR'))
            except:
                return render.problem(msg)

        attribs = list_account_attributes(ui_account)
        js_token = __to_js('token', token)
        js_account = __to_js('account', def_account)
    else:
        # if there is no session token or if invalid: get a new one.
        if validate_token is None:
            # get all accounts for an identity. Needed for account switcher in UI.
            accounts = identity.list_accounts_for_identity(dn, 'x509')
            if len(accounts) == 0:
                return render.problem(msg)

            cookie_accounts = accounts

            # try to set the default account to the user account, if not available take the first account.
            def_account = accounts[0]
            for account in accounts:
                account_info = get_account_info(account)
                if account_info.account_type == AccountType.USER:
                    def_account = account
                    break

            selected_account = cookies().get('rucio-selected-account')
            if (selected_account):
                def_account = selected_account
            try:
                token = authentication.get_auth_token_x509(
                    def_account, dn, 'webui', ctx.env.get('REMOTE_ADDR'))
            except:
                return render.problem(msg)

            attribs = list_account_attributes(def_account)
            # write the token and account to javascript variables, that will be used in the HTML templates.
            js_token = __to_js('token', token)
            js_account = __to_js('account', def_account)

    # if there was no valid session token write the new token to a cookie.
    if token:
        setcookie('x-rucio-auth-token', value=token, path='/')
        setcookie('rucio-auth-token-created-at', value=int(time()), path='/')

    if cookie_accounts:
        values = ""
        for acc in cookie_accounts:
            values += acc + " "
        setcookie('rucio-available-accounts', value=values[:-1], path='/')

    if attribs:
        setcookie('rucio-account-attr', value=dumps(attribs), path='/')

    if ui_account:
        setcookie('rucio-selected-account', value=ui_account, path='/')
    return render.base(js_token, js_account, rucio_ui_version, rendered_tpl)
Esempio n. 13
0
    def get(self, account):
        """
        ---
        summary: List account parameters
        description: Lists all parameters for an account.
        tags:
          - Account
        parameters:
        - name: account
          in: path
          description: The account identifier.
          schema:
            type: string
          style: simple
        responses:
          201:
            description: OK
            content:
              application/json:
                schema:
                  type: object
                  properties:
                    account:
                      description: The account identifier.
                      type: string
                    account_type:
                      description: The account type.
                      type: string
                    status:
                      description: The account status.
                      type: string
                    email:
                      description: The email for the account.
                      type: string
                    suspended_at:
                      description: Datetime if the account was suspended.
                      type: string
                    deleted_at:
                      description: Datetime if the account was deleted.
                      type: string
          401:
            description: Invalid Auth Token
          404:
            description: No account found.
          406:
            description: Not acceptable
        """
        if account == 'whoami':
            # Redirect to the account uri
            frontend = request.headers.get('X-Requested-Host', default=None)
            if frontend:
                return redirect(
                    f'{frontend}/accounts/{request.environ.get("issuer")}',
                    code=302)
            return redirect(request.environ.get('issuer'), code=303)

        try:
            acc = get_account_info(account, vo=request.environ.get('vo'))
        except AccountNotFound as error:
            return generate_http_error_flask(404, error)
        except AccessDenied as error:
            return generate_http_error_flask(401, error)

        accdict = acc.to_dict()

        for key, value in accdict.items():
            if isinstance(value, datetime):
                accdict[key] = value.strftime('%Y-%m-%dT%H:%M:%S')

        del accdict['_sa_instance_state']

        return Response(render_json(**accdict),
                        content_type="application/json")
Esempio n. 14
0
File: utils.py Progetto: zlion/rucio
def saml_authentication(method, rendered_tpl):
    """
    Login with SAML

    :param method: method type, GET or POST
    :param rendered_tpl: page to be rendered
    """

    attribs = None
    token = None
    js_token = ""
    js_account = ""
    def_account = None
    accounts = None
    cookie_accounts = None
    rucio_ui_version = version.version_string()
    policy = config_get('policy', 'permission')

    # Initialize variables for sending SAML request
    SAML_PATH = join(dirname(__file__), 'saml/')
    request = ctx.env
    data = dict(input())
    req = prepare_webpy_request(request, data)
    auth = OneLogin_Saml2_Auth(req, custom_base_path=SAML_PATH)

    saml_user_data = cookies().get('saml-user-data')

    render = template.render(join(dirname(__file__), '../templates'))

    session_token = cookies().get('x-rucio-auth-token')
    validate_token = authentication.validate_auth_token(session_token)

    if method == "GET":
        # If user data is not present, redirect to IdP for authentication
        if not saml_user_data:
            return seeother(auth.login())

        # If user data is present and token is valid, render the required page
        elif validate_token:
            js_token = __to_js('token', session_token)
            js_account = __to_js('account', def_account)

            return render.base(js_token, js_account, rucio_ui_version, policy,
                               rendered_tpl)

        # If user data is present but token is not valid, create a new one
        saml_nameid = cookies().get('saml-nameid')
        accounts = identity.list_accounts_for_identity(saml_nameid, 'saml')

        cookie_accounts = accounts
        try:
            token = authentication.get_auth_token_saml(
                def_account, saml_nameid, 'webui',
                ctx.env.get('REMOTE_ADDR')).token

        except:
            return render.problem('Cannot get auth token')

        attribs = list_account_attributes(def_account)
        # write the token and account to javascript variables, that will be used in the HTML templates.
        js_token = __to_js('token', token)
        js_account = __to_js('account', def_account)

        set_cookies(token, cookie_accounts, attribs)

        return render.base(js_token, js_account, rucio_ui_version, policy,
                           rendered_tpl)

    # If method is POST, check the received SAML response and redirect to home if valid
    auth.process_response()
    errors = auth.get_errors()
    if not errors:
        if auth.is_authenticated():
            setcookie('saml-user-data', value=auth.get_attributes(), path='/')
            setcookie('saml-session-index',
                      value=auth.get_session_index(),
                      path='/')
            setcookie('saml-nameid', value=auth.get_nameid(), path='/')
            saml_nameid = auth.get_nameid()

            accounts = identity.list_accounts_for_identity(saml_nameid, 'saml')
            cookie_accounts = accounts
            # try to set the default account to the user account, if not available take the first account.
            def_account = accounts[0]
            for account in accounts:
                account_info = get_account_info(account)
                if account_info.account_type == AccountType.USER:
                    def_account = account
                    break

            selected_account = cookies().get('rucio-selected-account')
            if (selected_account):
                def_account = selected_account

            try:
                token = authentication.get_auth_token_saml(
                    def_account, saml_nameid, 'webui',
                    ctx.env.get('REMOTE_ADDR')).token

            except:
                return render.problem('Cannot get auth token')

            attribs = list_account_attributes(def_account)
            # write the token and account to javascript variables, that will be used in the HTML templates.
            js_token = __to_js('token', token)
            js_account = __to_js('account', def_account)

            set_cookies(token, cookie_accounts, attribs)

            return seeother("/")

        return render.problem("Not authenticated")

    return render.problem("Error while processing SAML")
Esempio n. 15
0
File: utils.py Progetto: zlion/rucio
def log_in(data, rendered_tpl):
    attribs = None
    token = None
    js_token = ""
    js_account = ""
    def_account = None
    accounts = None
    cookie_accounts = None
    rucio_ui_version = version.version_string()
    policy = config_get('policy', 'permission')

    render = template.render(join(dirname(__file__), '../templates'))

    # # try to get and check the rucio session token from cookie
    session_token = cookies().get('x-rucio-auth-token')
    validate_token = authentication.validate_auth_token(session_token)

    # if token is valid, render the requested page.
    if validate_token and not data:
        token = session_token
        js_token = __to_js('token', token)
        js_account = __to_js('account', def_account)

        return render.base(js_token, js_account, rucio_ui_version, policy,
                           rendered_tpl)

    else:
        # if there is no session token or if invalid: get a new one.
        # if user tries to access a page through URL without logging in, then redirect to login page.
        if rendered_tpl:
            return render.login()

        # get all accounts for an identity. Needed for account switcher in UI.
        accounts = identity.list_accounts_for_identity(data.username,
                                                       'userpass')
        if len(accounts) == 0:
            return render.problem('No accounts for the given identity.')

        cookie_accounts = accounts
        # try to set the default account to the user account, if not available take the first account.
        def_account = accounts[0]
        for account in accounts:
            account_info = get_account_info(account)
            if account_info.account_type == AccountType.USER:
                def_account = account
                break

        selected_account = cookies().get('rucio-selected-account')
        if (selected_account):
            def_account = selected_account

        try:
            token = authentication.get_auth_token_user_pass(
                def_account, data.username, data.password.encode("ascii"),
                'webui', ctx.env.get('REMOTE_ADDR')).token

        except:
            return render.problem('Cannot get auth token')

        attribs = list_account_attributes(def_account)
        # write the token and account to javascript variables, that will be used in the HTML templates.
        js_token = __to_js('token', token)
        js_account = __to_js('account', def_account)

    set_cookies(token, cookie_accounts, attribs)

    return seeother('/')