Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

python changes for orgs api uptake #812

Closed
wants to merge 63 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
63 commits
Select commit Hold shift + click to select a range
dd72ebe
chore: oauth sdk implementation (#804)
manisha1997 Jul 22, 2024
0cd40b5
chore: update intersphinx_mapping (#807)
tiwarishubham635 Aug 2, 2024
fdd6edc
chore: preview iam removal (#808)
manisha1997 Aug 12, 2024
2b875ec
chore: add license identifier to project metadata (#810)
mschoettle Aug 23, 2024
f4e7765
[Librarian] Regenerated @ c8ce9820730ef3b2a48912311d45afb8c26b9ee7 2e…
twilio-dx Aug 26, 2024
e848451
Release 9.2.4
twilio-dx Aug 26, 2024
ba7da14
[Librarian] Regenerated @ 78bf2bbef74e4846ca8353fbdee038a6b8080c59 22…
twilio-dx Sep 5, 2024
74b506e
Release 9.3.0
twilio-dx Sep 5, 2024
3e246e4
Python Orgs Api Changes
AsabuHere Sep 17, 2024
8395487
removing unwanted logs
AsabuHere Sep 17, 2024
bc5c16b
removing unwanted logs
AsabuHere Sep 17, 2024
a66f9e9
removing unwanted logs
AsabuHere Sep 17, 2024
b5a6490
removing unwanted logs
AsabuHere Sep 17, 2024
fac26ee
Fixing token fetch flow
AsabuHere Sep 17, 2024
3eacd66
chore: add static init file to iam domain (#813)
tiwarishubham635 Sep 18, 2024
e595e28
[Librarian] Regenerated @ 1b6718f23da76f150eac392860c66a26de9af713 ce…
twilio-dx Sep 18, 2024
4168b09
Release 9.3.1
twilio-dx Sep 18, 2024
75e8b14
[Librarian] Regenerated @ 08245333f4a8c9235d547b189cd9c422f73e0e7e 7b…
twilio-dx Sep 25, 2024
0f81bbb
Release 9.3.2
twilio-dx Sep 25, 2024
15e15c0
twilio python changes for orgs api uptake
AsabuHere Sep 26, 2024
7b07ba7
twilio python changes for orgs api uptake
AsabuHere Sep 26, 2024
af11fd2
Update test_cluster.py
AsabuHere Sep 26, 2024
661785d
Update test_cluster.py
AsabuHere Sep 26, 2024
6a8c2d8
twilio python changes for orgs api uptake
AsabuHere Sep 26, 2024
1ba2f9b
twilio python changes for orgs api uptake
AsabuHere Sep 26, 2024
98708f0
twilio python changes for orgs api uptake
AsabuHere Sep 26, 2024
d78d5d5
twilio python changes for orgs api uptake
AsabuHere Sep 26, 2024
7bdf1b5
Merge branch 'main' into asabu_Python_changes
AsabuHere Sep 26, 2024
bc77770
twilio python changes for orgs api uptake
AsabuHere Sep 27, 2024
0211f23
twilio python changes for orgs api uptake
AsabuHere Sep 27, 2024
27dec32
twilio python changes for orgs api uptake
AsabuHere Sep 27, 2024
2959689
twilio python changes for orgs api uptake
AsabuHere Sep 27, 2024
b973065
Uptake of review comments
AsabuHere Oct 1, 2024
ceebd46
modified error messages
AsabuHere Oct 1, 2024
7fc68cb
chore: add assistants init files (#816)
tiwarishubham635 Oct 3, 2024
726c36a
[Librarian] Regenerated @ 021bab52f93b55d7a5786bd27716bf3a0be2d7b9 aa…
twilio-dx Oct 3, 2024
69b9ae8
Release 9.3.3
twilio-dx Oct 3, 2024
35b5015
Uptake of review comments
AsabuHere Oct 6, 2024
76fecab
Merge branch 'main' into asabu_Python_changes
AsabuHere Oct 6, 2024
ccce713
[Librarian] Regenerated @ d97b0740a0c7cf86beebd56c6973927b07719cde 1f…
twilio-dx Oct 17, 2024
9f1414d
Release 9.3.4
twilio-dx Oct 17, 2024
086bc6b
[Librarian] Regenerated @ 2e932f6c59e0f9fb6cb96952802e5ebedd83b6f0 18…
twilio-dx Oct 24, 2024
19e54f9
Release 9.3.5
twilio-dx Oct 24, 2024
efa2803
chore: removing unavailable references from init files (#818)
tiwarishubham635 Oct 25, 2024
15ee3e6
[Librarian] Regenerated @ 2e932f6c59e0f9fb6cb96952802e5ebedd83b6f0 18…
twilio-dx Oct 25, 2024
3fc2d25
Release 9.3.6
twilio-dx Oct 25, 2024
5aa42dc
chore: use older verison of aiohttp_retry (#819)
sbansla Oct 28, 2024
4f1e7d2
[Librarian] Regenerated @ 51e40434baa37a97b298d416220c6de10d9698c4 1a…
twilio-dx Nov 15, 2024
ce5ce5d
Release 9.3.7
twilio-dx Nov 15, 2024
bae3eca
[Librarian] Regenerated @ 45fa5159053e1c1f62f6d613f3b67a9239b43a5f 25…
twilio-dx Dec 5, 2024
fb53889
Release 9.3.8
twilio-dx Dec 5, 2024
e9eaa72
Organization api uptake changes
AsabuHere Dec 11, 2024
1c8420c
Organization api uptake changes
AsabuHere Dec 11, 2024
644f94b
Organization api uptake changes
AsabuHere Dec 11, 2024
66f3e28
Organization api uptake changes
AsabuHere Dec 11, 2024
88f6623
removing accept headers for delete operation
AsabuHere Dec 12, 2024
630c28c
Removing unwanted code
AsabuHere Dec 12, 2024
26ee4d3
Merge branch 'main' into asabu_Python_changes
AsabuHere Dec 12, 2024
ddb336b
Modified generated files
AsabuHere Dec 12, 2024
d79366e
removing unwamted logs
AsabuHere Dec 12, 2024
824ed9f
Formatting changes
AsabuHere Dec 12, 2024
3670f03
make prettier run
AsabuHere Dec 12, 2024
eafd8dd
Adding examples and pushing client token manager and cred provider
AsabuHere Dec 12, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 144 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,150 @@ twilio-python Changelog

Here you can see the full list of changes between each twilio-python release.

[2024-12-05] Version 9.3.8
--------------------------
**Api**
- Add optional parameter `intelligence_service` to `transcription`
- Updated `phone_number_sid` to be populated for sip trunking terminating calls.

**Numbers**
- Add Update Hosted Number Order V2 API endpoint
- Update Port in docs

**Twiml**
- Add optional parameter `intelligence_service` to `<Transcription>`
- Add support for new `<ConversationRelay>` and `<Assistant>` noun
- Add `events` attribute to `<Dial>` verb


[2024-11-15] Version 9.3.7
--------------------------
**Library - Chore**
- [PR #819](https://github.com/twilio/twilio-python/pull/819): use older verison of aiohttp_retry. Thanks to [@sbansla](https://github.com/sbansla)!

**Api**
- Added `ivr-virtual-agent-custom-voices` and `ivr-virtual-agent-genai` to `usage_record` API.
- Add open-api file tag to realtime_transcriptions

**Taskrouter**
- Add `api-tag` property to workers reservation
- Add `api-tag` property to task reservation


[2024-10-25] Version 9.3.6
--------------------------
**Library - Chore**
- [PR #818](https://github.com/twilio/twilio-python/pull/818): removing unavailable references from init files. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)!


[2024-10-24] Version 9.3.5
--------------------------
**Conversations**
- Expose ConversationWithParticipants resource that allows creating a conversation with participants


[2024-10-17] Version 9.3.4
--------------------------
**Api**
- Add response key `country` to fetch AvailablePhoneNumber resource by specific country.

**Messaging**
- Make library and doc public for requestManagedCert Endpoint


[2024-10-03] Version 9.3.3
--------------------------
**Library - Chore**
- [PR #816](https://github.com/twilio/twilio-python/pull/816): add assistants init files. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)!

**Messaging**
- Add A2P external campaign CnpMigration flag

**Numbers**
- Add address sid to portability API

**Verify**
- Add `SnaClientToken` optional parameter on Verification check.
- Add `EnableSnaClientToken` optional parameter for Verification creation.


[2024-09-25] Version 9.3.2
--------------------------
**Accounts**
- Update docs and mounts.
- Change library visibility to public
- Enable consent and contact bulk upsert APIs in prod.

**Serverless**
- Add is_plugin parameter in deployments api to check if it is plugins deployment


[2024-09-18] Version 9.3.1
--------------------------
**Library - Chore**
- [PR #813](https://github.com/twilio/twilio-python/pull/813): add static init file to iam domain. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)!

**Intelligence**
- Remove public from operator_type
- Update operator_type to include general-availablity and deprecated

**Numbers**
- Remove beta flag for bundle clone API


[2024-09-05] Version 9.3.0
--------------------------
**Iam**
- updated library_visibility public for new public apikeys

**Numbers**
- Add new field in Error Codes for Regulatory Compliance.
- Change typing of Port In Request date_created field to date_time instead of date **(breaking change)**


[2024-08-26] Version 9.2.4
--------------------------
**Library - Chore**
- [PR #810](https://github.com/twilio/twilio-python/pull/810): add license identifier to project metadata. Thanks to [@mschoettle](https://github.com/mschoettle)!
- [PR #808](https://github.com/twilio/twilio-python/pull/808): preview iam removal. Thanks to [@manisha1997](https://github.com/manisha1997)!
- [PR #807](https://github.com/twilio/twilio-python/pull/807): update intersphinx_mapping. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)!
- [PR #804](https://github.com/twilio/twilio-python/pull/804): add init file. Thanks to [@manisha1997](https://github.com/manisha1997)!

**Api**
- Update documentation of `error_code` and `error_message` on the Message resource.
- Remove generic parameters from `transcription` resource
- Added public documentation for Payload Data retrieval API

**Flex**
- Adding update Flex User api

**Insights**
- Added 'branded', 'business_profile' and 'voice_integrity' fields in List Call Summary

**Intelligence**
- Add `words` array information to the Sentences v2 entity.
- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` headers for Operator Results.
- Change the path parameter when fetching an `/OperatorType/{}` from `sid<EY>` to `string` to support searching by SID or by name
- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` headers for Transcript and Service endpoints.

**Messaging**
- Adds two new channel senders api to add/remove channel senders to/from a messaging service
- Extend ERC api to accept an optional attribute in request body to indicate CNP migration for an ERC

**Numbers**
- Modify visibility to public in bundle clone API
- Add `port_date` field to Port In Request and Port In Phone Numbers Fetch APIs
- Change properties docs for port in phone numbers api
- Add is_test body param to the Bundle Create API
- Change properties docs for port in api

**Trusthub**
- Add new field in themeSetId in compliance_inquiry.

**Verify**
- Update `custom_code_enabled` description on verification docs


[2024-07-02] Version 9.2.3
--------------------------
**Intelligence**
Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ After a brief delay, you will receive the text message on your phone.
> **Warning**
> It's okay to hardcode your credentials when testing locally, but you should use environment variables to keep them secret before committing any code or deploying to production. Check out [How to Set Environment Variables](https://www.twilio.com/blog/2017/01/how-to-set-environment-variables.html) for more information.

## OAuth Feature for Twilio APIs
We are introducing Client Credentials Flow-based OAuth 2.0 authentication. This feature is currently in beta and its implementation is subject to change.

API examples [here](https://github.com/twilio/twilio-python/blob/main/examples/public_oauth.py)

Organisation API examples [here](https://github.com/twilio/twilio-python/blob/main/examples/organization_api_calls.py)

## Use the helper library

### API Credentials
Expand Down
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,4 @@
# -- Options for intersphinx extension ---------------------------------------

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {"https://docs.python.org/": None}
intersphinx_mapping = {"python": ("https://docs.python.org/3", None)}
28 changes: 28 additions & 0 deletions examples/organization_api_calls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import os

from twilio.rest import Client
from twilio.credential.orgs_credential_provider import OrgsCredentialProvider

API_KEY = os.environ.get("TWILIO_API_KEY")
API_SECRET = os.environ.get("TWILIO_API_SECRET")
ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID")
CLIENT_ID = os.environ.get("TWILIO_CLIENT_ID")
CLIENT_SECRET = os.environ.get("TWILIO_CLIENT_SECRET")
ORGS_SID = os.environ.get("TWILIO_ORGS_SID")


def example(self=None):
"""
Some example usage of fetching accounts within an organization
"""
self.client = Client(
username=API_KEY,
password=API_SECRET,
account_sid=ACCOUNT_SID,
credential_provider= OrgsCredentialProvider(CLIENT_ID, CLIENT_SECRET)
)
accounts = self.client.preview_iam.organization(organization_sid=ORGS_SID).accounts.stream()
self.assertIsNotNone(accounts)

if __name__ == "__main__":
example()
35 changes: 35 additions & 0 deletions examples/public_oauth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import os

from twilio.rest import Client
from twilio.credential.client_credential_provider import ClientCredentialProvider

API_KEY = os.environ.get("TWILIO_API_KEY")
API_SECRET = os.environ.get("TWILIO_API_SECRET")
ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID")
CLIENT_ID = os.environ.get("TWILIO_CLIENT_ID")
CLIENT_SECRET = os.environ.get("TWILIO_CLIENT_SECRET")
ORGS_SID = os.environ.get("TWILIO_ORGS_SID")
FROM_NUMBER = os.environ.get("TWILIO_FROM_NUMBER")
TO_NUMBER = os.environ.get("TWILIO_TO_NUMBER")


def example(self=None):
"""
Some example usage of fetching accounts within an organization
"""
self.client = Client(
username=API_KEY,
password=API_SECRET,
account_sid=ACCOUNT_SID,
credential_provider= ClientCredentialProvider(CLIENT_ID, CLIENT_SECRET)
)
msg = self.client.messages.create(
to=self.to_number, from_=self.from_number, body="hello world"
)
self.assertEqual(msg.to, self.to_number)
self.assertEqual(msg.from_, self.from_number)
self.assertEqual(msg.body, "hello world")
self.assertIsNotNone(msg.sid)

if __name__ == "__main__":
example()
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ pygments>=2.7.4 # not directly required, pinned by Snyk to avoid a vulnerability
requests>=2.31.0
PyJWT>=2.0.0, <3.0.0
aiohttp>=3.9.4
aiohttp-retry>=2.8.3
aiohttp-retry==2.8.3
certifi>=2023.7.22 # not directly required, pinned by Snyk to avoid a vulnerability
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ universal = 1

[metadata]
description-file = README.md
license = MIT

[flake8]
exclude = ./twilio/rest,./twilio/twiml,./tests/integration
Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

setup(
name="twilio",
version="9.2.3",
version="9.3.8",
description="Twilio API client and TwiML generator",
author="Twilio",
help_center="https://www.twilio.com/help/contact",
Expand All @@ -24,7 +24,7 @@
"requests >= 2.0.0",
"PyJWT >= 2.0.0, < 3.0.0",
"aiohttp>=3.8.4",
"aiohttp-retry>=2.8.3",
"aiohttp-retry==2.8.3",
],
packages=find_packages(exclude=["tests", "tests.*"]),
include_package_data=True,
Expand Down
2 changes: 1 addition & 1 deletion twilio/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
__version_info__ = ("9", "2", "3")
__version_info__ = ("9", "3", "8")
__version__ = ".".join(__version_info__)
Empty file.
19 changes: 19 additions & 0 deletions twilio/auth_strategy/auth_strategy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from twilio.auth_strategy.auth_type import AuthType
from abc import abstractmethod


class AuthStrategy(object):
def __init__(self, auth_type: AuthType):
self._auth_type = auth_type

@property
def auth_type(self) -> AuthType:
return self._auth_type

@abstractmethod
def get_auth_string(self) -> str:
"""Return the authentication string."""

@abstractmethod
def requires_authentication(self) -> bool:
"""Return True if authentication is required, else False."""
12 changes: 12 additions & 0 deletions twilio/auth_strategy/auth_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from enum import Enum


class AuthType(Enum):
ORGS_TOKEN = "orgs_stoken"
NO_AUTH = "noauth"
BASIC = "basic"
API_KEY = "api_key"
CLIENT_CREDENTIALS = "client_credentials"

def __str__(self):
return self.value
13 changes: 13 additions & 0 deletions twilio/auth_strategy/no_auth_strategy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from auth_type import AuthType
from twilio.auth_strategy.auth_strategy import AuthStrategy


class NoAuthStrategy(AuthStrategy):
def __init__(self):
super().__init__(AuthType.NO_AUTH)

def get_auth_string(self) -> str:
return ""

def requires_authentication(self) -> bool:
return False
53 changes: 53 additions & 0 deletions twilio/auth_strategy/token_auth_strategy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import jwt
import threading
import logging
from datetime import datetime

from twilio.auth_strategy.auth_type import AuthType
from twilio.auth_strategy.auth_strategy import AuthStrategy
from twilio.http.token_manager import TokenManager


class TokenAuthStrategy(AuthStrategy):
def __init__(self, token_manager: TokenManager):
super().__init__(AuthType.ORGS_TOKEN)
self.token_manager = token_manager
self.token = None
self.lock = threading.Lock()
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger(__name__)

def get_auth_string(self) -> str:
self.fetch_token()
return f"Bearer {self.token}"

def requires_authentication(self) -> bool:
return True

def fetch_token(self):
if self.token is None or self.token == "" or self.is_token_expired(self.token):
with self.lock:
if (
self.token is None
or self.token == ""
or self.is_token_expired(self.token)
):
self.logger.info("New token fetched for accessing organization API")
self.token = self.token_manager.fetch_access_token()

def is_token_expired(self, token):
try:
decoded = jwt.decode(token, options={"verify_signature": False})

Check failure

Code scanning / SonarCloud

JWT should be signed and verified

<!--SONAR_ISSUE_KEY:AZO5eXCTuNV6EPBVA_gL-->Don't use a JWT token without verifying its signature. <p>See more on <a href="https://sonarcloud.io/project/issues?id=twilio_twilio-python&issues=AZO5eXCTuNV6EPBVA_gL&open=AZO5eXCTuNV6EPBVA_gL&branch=asabu_Python_changes">SonarQube Cloud</a></p>
exp = decoded.get("exp")

if exp is None:
return True # No expiration time present, consider it expired

# Check if the expiration time has passed
return datetime.fromtimestamp(exp) < datetime.utcnow()

except jwt.DecodeError:
return True # Token is invalid
except Exception as e:
print(f"An error occurred: {e}")
return True
Loading
Loading