aws-sso-lib


Nameaws-sso-lib JSON
Version 1.14.0 PyPI version JSON
download
home_pagehttps://github.com/benkehoe/aws-sso-util/blob/master/lib/README.md
SummaryLibrary to make AWS SSO easier
upload_time2023-01-27 00:47:00
maintainer
docs_urlNone
authorBen Kehoe
requires_python>=3.7,<4.0
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # `aws-sso-lib`

`aws-sso-lib` allows you to programmatically interact with AWS IAM Identity Center (formerly AWS SSO).

The primary functions that will be of interest are available at the package level:
* `get_boto3_session`: Get a boto3 session for a specific account and role.
* `login`: ensure the user is logged in to Identity Center, with dispatch to the browser.
* `list_available_accounts` and `list_available_roles`: discover the access the user has.
* `list_assignments`: for admin purposes, iterate over all assignments in Identity Center, which is currently hard to do through the API.

`aws-sso-util` is a command-line utility built on `aws-sso-lib` for interacting with Identity Center; see the details of that project [here](https://github.com/benkehoe/aws-sso-util).

## Install

```
pip install --user aws-sso-lib
python -c "import aws_sso_lib; aws_sso_lib.login('https://my-start-url.awsapps.com/start', 'us-east-2')"
```

## `get_boto3_session`

Often when writing a script, you know the exact account and role you want the script to use.
You could configure a profile in your `~/.aws/config` for this (perhaps using `aws-sso-util configure profile`), but especially if multiple people may be using the script, it's more convenient to have the configuration baked into the script itself.
`get_boto3_session()` is the function to do that with.

```python
get_boto3_session(start_url, sso_region, account_id, role_name, *, region,
    login=False,
    sso_cache=None,
    credential_cache=None)
```

* `start_url`: [REQUIRED] The start URL for the Identity Center instance.
* `sso_region`: [REQUIRED] The AWS region for the Identity Center instance.
* `account_id`: [REQUIRED] The AWS account ID to use.
* `role_name`: [REQUIRED] The Identity Center role (aka PermissionSet) name to use.
* `region`: [REQUIRED] The AWS region for the boto3 session (note, required but keyword-only).
* `login`: Set to `True` to interactively log in the user if their Identity Center credentials have expired.
* `sso_cache`: A dict or dict-like object for Identity Center credential caching to replace the default file cache in `~/.aws/sso/cache`.
* `credential_cache`: A dict or dict-like object to cache the role credentials in to replace the default in-memory cache.
* Returns a [boto3 Session object](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html) configured for the account and role.

For more control over the login process, use the `login` function separately.

## `login`

While the functions that require the user to be logged in let you specify `login=True` to interactively log in the user if they are not already logged in, you can have more control over the process, or retrieve the access token, using `login()`.

If the user is not logged in or `force_refresh` is `True`, it will attempt to log in.
If the user is logged in and `force_refresh` is `False`, no action is taken.

Normally, it will attempt to automatically open the user's browser to log in, as well as printing the URL and code to stderr as a fallback. However, if `disable_browser` is `True`, or if `disable_browser` is `None` (the default) and the environment variable `AWS_SSO_DISABLE_BROWSER` is set to `1` or `true`, only the message with the URL and code will be printed.

A custom message can be printed by setting `message` to a template string using `{url}` and `{code}` as placeholders.
The message can be suppressed by setting `message` to `False`.

To fully control the communication with the user, use the `user_auth_handler` parameter.
It must be a callable taking four keyword arguments: `verificationUri`, `userCode`, `verificationUriComplete`, and `expiresAt` (a datetime).
Provide `verificationUri` and `userCode` to the user if they are expected to type them in manually (e.g., on a separate device); `verificationUriComplete` has the userCode embedded in it, suitable for copying, linking, or a browser popup.
The function must return promptly or it will block the login process.

```python
login(start_url, sso_region, *,
    force_refresh=False,
    expiry_window=None,
    disable_browser=None,
    message=None,
    outfile=None,
    user_auth_handler=None,
    sso_cache=None)
```

* `start_url`: [REQUIRED] The start URL for the Identity Center instance.
* `sso_region`: [REQUIRED] The AWS region for the Identity Center instance.
* `force_refresh`: Set to `True` to always go through the authentication process.
* `expiry_window`: A datetime.timedelta (or number of seconds), or callable returning such, specifying the minimum duration any existing token must be valid for.
* `disable_browser`: Set to `True` to skip the browser popup and only print a message with the URL and code.
* `message`: A message template to print with the fallback URL and code, or `False` to suppress the message.
* `outfile`: The file-like object to print the message to (stderr by default)
* `user_auth_handler`: override browser popup and message printing and use the given function instead.
* `sso_cache`: A dict or dict-like object for Identity Center credential caching, to override the default file cache in `~/.aws/sso/cache`.
* Returns the token dict as returned by [sso-oidc:CreateToken](https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html), which contains the actual authorization token, as well as the expiration.

## `list_available_accounts` and `list_available_roles`

Identity Center provides programmatic access to the permissions that a user has.
You can access this through `list_available_accounts()` and `list_available_roles()`.

With both, you can set `login=True` to interactively log in the user if they are not already logged in.

Note that these functions return iterators; they don't return a list, because the number of roles may be very large and you shouldn't have to wait for the entire list to be created to start processing.
You can always get a list by, for example, `list(list_available_roles(...))`.

```python
list_available_accounts(start_url, sso_region, *, login=False)
```

* `start_url`: The start URL for the Identity Center instance.
* `sso_region`: The AWS region for the Identity Center instance.
* `login`: Set to `True` to interactively log in the user if their Identity Center credentials have expired.
* Returns an iterator that yields account id and account name.

```python
list_available_roles(start_url, sso_region, account_id=None, *, login=False)
```

* `start_url`: [REQUIRED] The start URL for the Identity Center instance.
* `sso_region`: [REQUIRED] The AWS region for the Identity Center instance.
* `account_id`: Optional account id or list of account ids to check.
  * If not set, all accounts available to the user are used.
* `login`: Set to `True` to interactively log in the user if their Identity Center credentials have expired.
* Returns an iterator that yields account id, account name, and role name.

## `list_assignments`

The Identity Center API only allows you to [list assignments for a specific account _and_ permission set](https://docs.aws.amazon.com/singlesignon/latest/APIReference/API_ListAccountAssignments.html).
To find all your assignments, you need to iterate over all accounts, and then interate over all permission sets.
`list_assignments()` does this work for you.

Unlike the other functions list above, this uses admin APIs, which require AWS credentials, rather than taking as input a start URL and region.

`list_assignments` returns an iterator over `Assignment` named tuples, which have the following fields:

* `instance_arn`
* `principal_type`
* `principal_id`
* `principal_name`
* `permission_set_arn`
* `permission_set_name`
* `target_type`
* `target_id`
* `target_name`

The name fields may be `None`, if the names are not known or looked up.
By default, principal and permission set names are not retrieved, nor are account names for accounts that have been provided as explicit targets.

If you don't specify `instance_arn` and/or `identity_store_id`, these will be looked up using the [ListInstances API](https://docs.aws.amazon.com/singlesignon/latest/APIReference/API_ListInstances.html), which today returns at most one instance (with associated identity store).

An assignment is the combination of a principal (a user or a group), a permission set, and a target (an AWS account).
For each of these values, you can provide either an explicit specification, or a filter function.

You can provide an OU as a target, which will use all accounts in that OU, and optionally all accounts recursively in child OUs as well.

```python
list_assignments(
    session,
    instance_arn=None,
    identity_store_id=None,
    principal=None,
    principal_filter=None,
    permission_set=None,
    permission_set_filter=None,
    target=None,
    target_filter=None,
    get_principal_names=False,
    get_permission_set_names=False,
    get_target_names=False,
    ou_recursive=False)
```

* `session`: [REQUIRED] boto3 session to use
* `instance_arn`: The Identity Center instance to use, or it will be looked up using ListInstances
* `identity_store_id`: The identity store to use if principal names are being retrieved or it will be looked up using ListInstances
* `principal`: A principal specification or list of principal specifications.
    * A principal specification is a principal id or a 2-tuple of principal type and id.
* `principal_filter`: A callable taking principal type, principal id, and principal name (which may be `None`), and returning `True` if the principal should be included.
* `permission_set`: A permission set arn or id, or a list of the same.
* `permission_set_filter`: A callable taking permission set arn and name (name may be `None`), returning True if the permission set should be included.
* `target`: A target specification or list of target specifications.
    * A target specification is an account or OU id, or a 2-tuple of target type, which is either AWS_ACCOUNT or AWS_OU, and target id.
* `target_filter`: A callable taking target type, target id, and target name (which may be `None`), and returning `True` if the target should be included.
* `get_principal_names`: Set to `True` to retrieve names for principals in assignments.
* ` get_permission_set_names`: Set to `True` to retrieve names for permission sets in assignments.
* `get_target_names`: Set to `True` to retrieve names for targets in assignments, when they are explicitly provided as targets. For OUs as targets or if no targets are specified, the account names will be retrieved automatically during the enumeration process.
* `ou_recursive`: Set to `True` if an OU is provided as a target to get all accounts including those in child OUs.
* Returns an iterator over `Assignment` tuples

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/benkehoe/aws-sso-util/blob/master/lib/README.md",
    "name": "aws-sso-lib",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7,<4.0",
    "maintainer_email": "",
    "keywords": "",
    "author": "Ben Kehoe",
    "author_email": "ben@kehoe.io",
    "download_url": "https://files.pythonhosted.org/packages/3d/df/302bafc5e7182212eec091269c4731bb4469041a1db5e6c3643d089d135d/aws_sso_lib-1.14.0.tar.gz",
    "platform": null,
    "description": "# `aws-sso-lib`\n\n`aws-sso-lib` allows you to programmatically interact with AWS IAM Identity Center (formerly AWS SSO).\n\nThe primary functions that will be of interest are available at the package level:\n* `get_boto3_session`: Get a boto3 session for a specific account and role.\n* `login`: ensure the user is logged in to Identity Center, with dispatch to the browser.\n* `list_available_accounts` and `list_available_roles`: discover the access the user has.\n* `list_assignments`: for admin purposes, iterate over all assignments in Identity Center, which is currently hard to do through the API.\n\n`aws-sso-util` is a command-line utility built on `aws-sso-lib` for interacting with Identity Center; see the details of that project [here](https://github.com/benkehoe/aws-sso-util).\n\n## Install\n\n```\npip install --user aws-sso-lib\npython -c \"import aws_sso_lib; aws_sso_lib.login('https://my-start-url.awsapps.com/start', 'us-east-2')\"\n```\n\n## `get_boto3_session`\n\nOften when writing a script, you know the exact account and role you want the script to use.\nYou could configure a profile in your `~/.aws/config` for this (perhaps using `aws-sso-util configure profile`), but especially if multiple people may be using the script, it's more convenient to have the configuration baked into the script itself.\n`get_boto3_session()` is the function to do that with.\n\n```python\nget_boto3_session(start_url, sso_region, account_id, role_name, *, region,\n    login=False,\n    sso_cache=None,\n    credential_cache=None)\n```\n\n* `start_url`: [REQUIRED] The start URL for the Identity Center instance.\n* `sso_region`: [REQUIRED] The AWS region for the Identity Center instance.\n* `account_id`: [REQUIRED] The AWS account ID to use.\n* `role_name`: [REQUIRED] The Identity Center role (aka PermissionSet) name to use.\n* `region`: [REQUIRED] The AWS region for the boto3 session (note, required but keyword-only).\n* `login`: Set to `True` to interactively log in the user if their Identity Center credentials have expired.\n* `sso_cache`: A dict or dict-like object for Identity Center credential caching to replace the default file cache in `~/.aws/sso/cache`.\n* `credential_cache`: A dict or dict-like object to cache the role credentials in to replace the default in-memory cache.\n* Returns a [boto3 Session object](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html) configured for the account and role.\n\nFor more control over the login process, use the `login` function separately.\n\n## `login`\n\nWhile the functions that require the user to be logged in let you specify `login=True` to interactively log in the user if they are not already logged in, you can have more control over the process, or retrieve the access token, using `login()`.\n\nIf the user is not logged in or `force_refresh` is `True`, it will attempt to log in.\nIf the user is logged in and `force_refresh` is `False`, no action is taken.\n\nNormally, it will attempt to automatically open the user's browser to log in, as well as printing the URL and code to stderr as a fallback. However, if `disable_browser` is `True`, or if `disable_browser` is `None` (the default) and the environment variable `AWS_SSO_DISABLE_BROWSER` is set to `1` or `true`, only the message with the URL and code will be printed.\n\nA custom message can be printed by setting `message` to a template string using `{url}` and `{code}` as placeholders.\nThe message can be suppressed by setting `message` to `False`.\n\nTo fully control the communication with the user, use the `user_auth_handler` parameter.\nIt must be a callable taking four keyword arguments: `verificationUri`, `userCode`, `verificationUriComplete`, and `expiresAt` (a datetime).\nProvide `verificationUri` and `userCode` to the user if they are expected to type them in manually (e.g., on a separate device); `verificationUriComplete` has the userCode embedded in it, suitable for copying, linking, or a browser popup.\nThe function must return promptly or it will block the login process.\n\n```python\nlogin(start_url, sso_region, *,\n    force_refresh=False,\n    expiry_window=None,\n    disable_browser=None,\n    message=None,\n    outfile=None,\n    user_auth_handler=None,\n    sso_cache=None)\n```\n\n* `start_url`: [REQUIRED] The start URL for the Identity Center instance.\n* `sso_region`: [REQUIRED] The AWS region for the Identity Center instance.\n* `force_refresh`: Set to `True` to always go through the authentication process.\n* `expiry_window`: A datetime.timedelta (or number of seconds), or callable returning such, specifying the minimum duration any existing token must be valid for.\n* `disable_browser`: Set to `True` to skip the browser popup and only print a message with the URL and code.\n* `message`: A message template to print with the fallback URL and code, or `False` to suppress the message.\n* `outfile`: The file-like object to print the message to (stderr by default)\n* `user_auth_handler`: override browser popup and message printing and use the given function instead.\n* `sso_cache`: A dict or dict-like object for Identity Center credential caching, to override the default file cache in `~/.aws/sso/cache`.\n* Returns the token dict as returned by [sso-oidc:CreateToken](https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html), which contains the actual authorization token, as well as the expiration.\n\n## `list_available_accounts` and `list_available_roles`\n\nIdentity Center provides programmatic access to the permissions that a user has.\nYou can access this through `list_available_accounts()` and `list_available_roles()`.\n\nWith both, you can set `login=True` to interactively log in the user if they are not already logged in.\n\nNote that these functions return iterators; they don't return a list, because the number of roles may be very large and you shouldn't have to wait for the entire list to be created to start processing.\nYou can always get a list by, for example, `list(list_available_roles(...))`.\n\n```python\nlist_available_accounts(start_url, sso_region, *, login=False)\n```\n\n* `start_url`: The start URL for the Identity Center instance.\n* `sso_region`: The AWS region for the Identity Center instance.\n* `login`: Set to `True` to interactively log in the user if their Identity Center credentials have expired.\n* Returns an iterator that yields account id and account name.\n\n```python\nlist_available_roles(start_url, sso_region, account_id=None, *, login=False)\n```\n\n* `start_url`: [REQUIRED] The start URL for the Identity Center instance.\n* `sso_region`: [REQUIRED] The AWS region for the Identity Center instance.\n* `account_id`: Optional account id or list of account ids to check.\n  * If not set, all accounts available to the user are used.\n* `login`: Set to `True` to interactively log in the user if their Identity Center credentials have expired.\n* Returns an iterator that yields account id, account name, and role name.\n\n## `list_assignments`\n\nThe Identity Center API only allows you to [list assignments for a specific account _and_ permission set](https://docs.aws.amazon.com/singlesignon/latest/APIReference/API_ListAccountAssignments.html).\nTo find all your assignments, you need to iterate over all accounts, and then interate over all permission sets.\n`list_assignments()` does this work for you.\n\nUnlike the other functions list above, this uses admin APIs, which require AWS credentials, rather than taking as input a start URL and region.\n\n`list_assignments` returns an iterator over `Assignment` named tuples, which have the following fields:\n\n* `instance_arn`\n* `principal_type`\n* `principal_id`\n* `principal_name`\n* `permission_set_arn`\n* `permission_set_name`\n* `target_type`\n* `target_id`\n* `target_name`\n\nThe name fields may be `None`, if the names are not known or looked up.\nBy default, principal and permission set names are not retrieved, nor are account names for accounts that have been provided as explicit targets.\n\nIf you don't specify `instance_arn` and/or `identity_store_id`, these will be looked up using the [ListInstances API](https://docs.aws.amazon.com/singlesignon/latest/APIReference/API_ListInstances.html), which today returns at most one instance (with associated identity store).\n\nAn assignment is the combination of a principal (a user or a group), a permission set, and a target (an AWS account).\nFor each of these values, you can provide either an explicit specification, or a filter function.\n\nYou can provide an OU as a target, which will use all accounts in that OU, and optionally all accounts recursively in child OUs as well.\n\n```python\nlist_assignments(\n    session,\n    instance_arn=None,\n    identity_store_id=None,\n    principal=None,\n    principal_filter=None,\n    permission_set=None,\n    permission_set_filter=None,\n    target=None,\n    target_filter=None,\n    get_principal_names=False,\n    get_permission_set_names=False,\n    get_target_names=False,\n    ou_recursive=False)\n```\n\n* `session`: [REQUIRED] boto3 session to use\n* `instance_arn`: The Identity Center instance to use, or it will be looked up using ListInstances\n* `identity_store_id`: The identity store to use if principal names are being retrieved or it will be looked up using ListInstances\n* `principal`: A principal specification or list of principal specifications.\n    * A principal specification is a principal id or a 2-tuple of principal type and id.\n* `principal_filter`: A callable taking principal type, principal id, and principal name (which may be `None`), and returning `True` if the principal should be included.\n* `permission_set`: A permission set arn or id, or a list of the same.\n* `permission_set_filter`: A callable taking permission set arn and name (name may be `None`), returning True if the permission set should be included.\n* `target`: A target specification or list of target specifications.\n    * A target specification is an account or OU id, or a 2-tuple of target type, which is either AWS_ACCOUNT or AWS_OU, and target id.\n* `target_filter`: A callable taking target type, target id, and target name (which may be `None`), and returning `True` if the target should be included.\n* `get_principal_names`: Set to `True` to retrieve names for principals in assignments.\n* ` get_permission_set_names`: Set to `True` to retrieve names for permission sets in assignments.\n* `get_target_names`: Set to `True` to retrieve names for targets in assignments, when they are explicitly provided as targets. For OUs as targets or if no targets are specified, the account names will be retrieved automatically during the enumeration process.\n* `ou_recursive`: Set to `True` if an OU is provided as a target to get all accounts including those in child OUs.\n* Returns an iterator over `Assignment` tuples\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "Library to make AWS SSO easier",
    "version": "1.14.0",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "50642b21ee0e5844b0a2c4ac29b344f37cf3dccda83b6d50a258469b24be07c5",
                "md5": "6e5eab62f535de1fba5ab65de81ac466",
                "sha256": "e09bf0f7d893691fb18967dadb4cddebd0c0ff9524fb76650bf366494a786304"
            },
            "downloads": -1,
            "filename": "aws_sso_lib-1.14.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6e5eab62f535de1fba5ab65de81ac466",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7,<4.0",
            "size": 33612,
            "upload_time": "2023-01-27T00:46:57",
            "upload_time_iso_8601": "2023-01-27T00:46:57.981498Z",
            "url": "https://files.pythonhosted.org/packages/50/64/2b21ee0e5844b0a2c4ac29b344f37cf3dccda83b6d50a258469b24be07c5/aws_sso_lib-1.14.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3ddf302bafc5e7182212eec091269c4731bb4469041a1db5e6c3643d089d135d",
                "md5": "50aafa7e787d05ce644cbe130ca75351",
                "sha256": "b0203a64ccb66ba78f99ef3d0eb669affe7bc323f6ab9caac97f35c21a03cea5"
            },
            "downloads": -1,
            "filename": "aws_sso_lib-1.14.0.tar.gz",
            "has_sig": false,
            "md5_digest": "50aafa7e787d05ce644cbe130ca75351",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7,<4.0",
            "size": 29404,
            "upload_time": "2023-01-27T00:47:00",
            "upload_time_iso_8601": "2023-01-27T00:47:00.141531Z",
            "url": "https://files.pythonhosted.org/packages/3d/df/302bafc5e7182212eec091269c4731bb4469041a1db5e6c3643d089d135d/aws_sso_lib-1.14.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-01-27 00:47:00",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "lcname": "aws-sso-lib"
}
        
Elapsed time: 0.05801s