GithubHelp home page GithubHelp logo

protonmail / proton-python-client Goto Github PK

View Code? Open in Web Editor NEW
340.0 23.0 62.0 1.71 MB

Python Proton client module

License: GNU General Public License v3.0

Python 94.97% Makefile 4.04% Shell 0.99%
python srp protonmail protonvpn api client

proton-python-client's Introduction

Proton API Python Client

Copyright (c) 2021 Proton Technologies AG

This repository holds the Proton Python Client. For licensing information see COPYING. For contribution policy see CONTRIBUTING.

Description

The Python Proton Client is intended for every Proton service user.

You can download the latest stable release, either from our official repositories or directly on the official GitHub repository.

Dependencies

Python Debian Fedora Arch
requests >= 2.16.0 * python3-requests python3-requests python-requests
bcrypt python3-bcrypt python3-bcrypt python-bcrypt
python-gnupg python3-gnupg python3-gnupg python-gnupg
pyopenssl python3-openssl python3-pyOpenSSL python-pyopenssl

* versions lower than 2.16 of the Python Requests library are not officially supported due to the missing support for TLS pinning, which is required in order to properly verify and trust the connection to the Proton API. It is possible disable TLS pinning (ie: to run with lower requests versions), but be aware of the risk.

Table of Contents

Install

The recommended way to install the client is via OS-respective packages (.deb/.rpm/.zst), by either compiling it yourself or downloading the binaries from our repositories. If for some reason that is not possible, then a normal python installation can be accomplished.

Usage

Import

from proton.api import Session, ProtonError

Setup

By default, TLS pinning is enabled. If you would like to disable it, you can additionally pass TLSPinning=False.

proton_session = Session(
    api_url="https://example.api.com",
    appversion="GithubExample_0.0.1",
    user_agent="Ubuntu_20.04",
)

api_url: The base API url

appversion: Usually this is the version of the application that is implementing the client. Leave it empty for non-official Proton clients.

user_agent: This helps us to understand on what type of platforms the client is being used. This usually can be fed with the output of a python package called distro. Leave empty in case of doubt.

Now that we've setup our Proton session, we're ready for authentication.

Authenticate

To authenticate against the Proton API, two types of information would need to be provided first, the Proton username and password.

proton_session.authenticate(username, password)

username: Proton username, ie: [email protected]

password: Proton password

After successfully authenticating against the API, we can now start using our proton_session object to make API calls. More on that in API calls.

Store session

To store the session locally on disk (for later re-use), we need to first extract its contents. To accomplish that we will need to use a method called dump(). This method returns a dict.

proton_session.dump()

The output of a dump will usually look something like this:

session_dump = proton_session.dump()
print(session_dump)
---
{"api_url": "https://example.api.com", "appversion": "GithubExample_0.0.1", "User-Agent": "Ubuntu_20.04", "cookies": {}, "session_data": {}}

If cookies and session_data contain no data, then it means that we've attempted to make an API call and it failed or we haven't made one yet.

If authenticated, session_data will contain some data that will be necessary for the Refresh Session chapter, in particular the keys AccessToken and RefreshToken.

Note: It is recommended to store the contents as JSON.

Load session

To re-use a session that we've previously stored we need to do as following:

  1. Get session contents
  2. Instantiate our session

If for example we've previously stored the session on a JSON file, then we would need to extract the session contents from file first (step 1):

with open(PATH_TO_JSON_SESSION_FILE, "r") as f:
    session_in_json_format = json.loads(f.read())

Now we can proceed with session instantiation (step 2):

proton_session = Session.load(
    dump=session_in_json_format
)

Now we're able to start using our proton_session object to make API calls. More on that in API calls.

Refresh Session

As previously introduced in the Store session chapter, AccessToken and RefreshToken are two tokens that identify us against the API. As their names imply, AccessToken is used to give us access to the API while RefreshToken is used to refresh the AccessToken whenever this one is invalidated by the servers. An AccessToken can be invalidated for the following reasons:

  • When the session is removed via the webclient
  • When a logout() is executed
  • When the session has expired

If for any reason the API responds with error 401, then it means that the AccessToken is invalid and it needs to be refreshed (assuming that the RefreshToken is valid). To refresh the tokens * we can use the following method:

proton_session.refresh()

Our tokens * have now been updated. To make sure that we can re-use this session with the refreshed tokens *, we can store them into file (or keyring). Consult the Store session chapter on how to accomplish that.

* when we use the refresh() method, both AccessToken and RefreshToken are refreshed.

API calls

Once we're authenticated and our tokens are valid, we can make api calls to various endpoints. By default a post request is made, unless another type of request is passed: method=get|post|put|delete|patch|None. Also additional custom headers can be sent with additional_headers="{'header': 'custom_header'}". Then to make the request we can use the following:

proton_session.api_request(endpoint="custom_api_endpoint")

Error handling

For all of commands presented in the previous chapters, it is recommended to use them within try/except blocks. Some common errors that might come up:

  • 401: Invalid AccessToken, client should refresh tokens (Refresh Session)
  • 403: Missing scopes, client should re-authenticate (logout and login)
  • 429: Too many requests. Retry after time provided by ProtonError.headers["Retry-After"]
  • 503: Unable to reach API (most probably API is down)
  • 8002: Provided password is wrong
  • 10002: Account is deleted
  • 10003: Account is disabled
  • 10013: RefreshToken is invalid. Client should re-authenticate (logout and login)

Below are some use cases:

  • Authentication
error_message = {
    8002: "Provided password is incorrect",
    10002: "Account is deleted",
    10003: "Account is disabled",
}
try:
    proton_session.authenticate("[email protected]", "Su!erS€cretPa§§word")
except ProtonError as e:
    print(error_message.get(e.code, "Unknown error")
  • API requests
error_message = {
    401: "Invalid access token, client should refresh tokens",
    403: "Missing scopes, client should re-authenticate",
    429: "Too many requests, client needs to retry after specified in headers",
    503: "API is unreacheable",
    10013: "Refresh token is invalid. Client should re-authenticate (logout and login)",
}

try:
    proton_session.api_request(endpoint="custom_api_endpoint")
except ProtonError as e:
    print(error_message.get(e.code, "Unknown error")
  • Refresh token
try:
    proton_session.api_request(endpoint="custom_api_endpoint")
except ProtonError as e:
    e.code == 401:
        proton_session.refresh()
        print("Now we can retry making another API call since tokens have been refreshed")

proton-python-client's People

Contributors

calexandru2018 avatar kaplun avatar wussler avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

proton-python-client's Issues

No priority support for PRO customers

I am a PRO customer, I can no longer send an email from my professional email address because address was blocked by protonmail. My professional activity is paralyzed. I made a request for support it 72 hours and I received no response. Is that what you call Priority Support for PRO customers? Here is the ticket number 940607

Generate and send report upon TLS-pinning failure

A report should be generated and sent in case of TLS-pinning failure, possibly containing the following info:

  • appVersion
  • appPlatform
  • appPlatformVersion
  • serverHostname
  • serverPort
  • dateTime
  • notedHostname
  • includeSubdomains
  • knownPins
  • validationResult
  • knownPinsExpirationDate

Email API Documentation?

Is there any documentation for actually using this API for sending and receiving emails?

The README just explains how to authenticate and store your authentication, and nothing else. Why authenticate if there's no functionality to authenticate for?

Unable to add authenticated "proxies" arg to protonmail Session

Tried formats Host:Port:User:Pass and User:Pass@Host:Port
Has anyone else had any success with this?

proton_session = Session(
        'https://api.protonmail.ch',
        path.join(cwd, log_folder),
        path.join(cwd, "cache"),
        tls_pinning=False,
        proxies="Host:Port:Username:Password"
)
proton_session.authenticate(username=proton_email, password=proton_password)    #does not authenticate with proxy

Failure on build

Hi I try to install protonvpn on Archlinux 5.18.2-arch1-1 from aur (yay -S protonvpn), but when the installer try to build proton-python-client-0.7.1 I get this error:

==> Starting build()...
Traceback (most recent call last):
  File "setup.py", line 4, in <module>
    from proton.constants import VERSION
  File "/home/carlos/.cache/yay/python-proton-client/src/proton-python-client-0.7.1/proton/__init__.py", line 1, in <module>
    from .api import Session # noqa
  File "/home/carlos/.cache/yay/python-proton-client/src/proton-python-client-0.7.1/proton/api.py", line 247
    exc_type, *_ = sys.exc_info()
              ^
SyntaxError: invalid syntax
==> ERROR: A failure occurred in build().
    Aborting...
 -> error making: python-proton-client

full log at https://pastebin.com/9RK21cVK

Any idea how to fix?, I try to search the issue but without luck.

Cheers.

Custom domain reply

The default mail adress is used as default to reply to mails even if the originaly sent email, and the response from the receiver, was done with another custom domain.

Protonmail should automatically find the adress that the mail thread belongs to (which account received the email) and set that as default when replying.

See "to" and "from" in image attached.

Skjermbilde 2023-03-14 kl  10 20 16

API calls documentation is nowhere to be found

Hey, thanks for this Python module, but I'm not sure I get it...

You provide Python code, talk about APIs, but you don't give a single API endpoint ? Is this repo for internal tooling purposes or do you plan to document the API at some point ?

No module named 'gnupg'

ModuleNotFoundError: No module named 'gnupg'
vadiki@localhost:/run/media/vadiki/D_238_GB_WD/proton-python-client-master> pip3 install gnupg
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: gnupg in /home/vadiki/.local/lib/python3.8/site-packages (2.3.1)
Requirement already satisfied: psutil>=1.2.1 in /usr/lib64/python3.8/site-packages (from gnupg) (5.9.0)

Respect retries

Proton API might return 429, with a retry-after header. This should be respected.

Make requests session permanent

Currently a new requests session is allocated on the fly per every request. This is suboptimal (and does not preserve cookies). We should rather allocate a session at class initialization and preserve it.

allow importing filters

I am checking whether Proton mail is capable of replacing Gmail, the first found blocker is lack of ability to import email filters.

Though maybe Sieve mentioned in settings can be one giant filter handling thousands of rules at once...

Note that even Gmail allows import/export of filters.

Alternative routing

In case of TLS-pinning failure or in case of unreachable handler, we should implement alternative routing as the other clients.

TLS Pinning

We need to implement TLS pinning for official APIs.

2FA

We shall introduce 2FA support

No priority support for PRO customers

I am a PRO customer, I can no longer send an email from my professional email address because my IP address was blocked by protonmail. My professional activity is paralyzed. I made a request for support it 48 hours and I received no response. Is that what you call Priority Support for PRO customers? Here is the ticket number 940607

Modernize

Hi,

I think this is critical:

  • Use setuptools not distutils in setup.py
  • python 2 is dead, buried and rotting
    ** so can ditch six

Opinion:

  • PEP8 is nice, black is better
  • use setup.cfg and a lean setup.py
  • add annotations

I'm happy to implement if agreed.

Missing declaration of urllib3<2 as a dependency

As others have pointed out ([1], [2]), the project directly uses urllib3 in a way not compatible with v2.x, what leads to the known Unknown API error in vpn apps.

But there is not only no upper bound on the compatible version. Currently the project does not declare a dependency on urllib3 at all.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.