• Stars
    star
    343
  • Rank 123,371 (Top 3 %)
  • Language
    Python
  • License
    GNU General Publi...
  • Created over 4 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Python Proton client module

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")

More Repositories

1

WebClients

Monorepo hosting the proton web clients
TypeScript
4,315
star
2

proton-mail-android

Proton Mail Android app
Kotlin
1,741
star
3

ios-mail

Secure email that protects your privacy
Swift
1,439
star
4

proton-bridge

Proton Mail Bridge application
Go
1,137
star
5

gopenpgp

A high-level OpenPGP library
Go
1,018
star
6

gluon

An IMAP server library written in Go
Go
339
star
7

go-crypto

Fork of go/x/crypto, providing an up-to-date OpenPGP implementation
Go
323
star
8

react-components

List of React components for Proton web-apps
TypeScript
177
star
9

proton-mail

React web application to manage ProtonMail
TypeScript
172
star
10

android-mail

Proton Mail Android app
Kotlin
141
star
11

protoncore_android

Proton Core components for Android
Kotlin
129
star
12

design-system

Design system for new Proton project
SCSS
124
star
13

proton-calendar

Proton Calendar built with React.
TypeScript
120
star
14

proton-drive

TypeScript
115
star
15

proton-shared

Shared logic for Proton web-app
TypeScript
71
star
16

go-appdir

Minimalistic Go package to get application directories such as config and cache
Go
63
star
17

inbox-desktop

Desktop application for Mail and Calendar, made with Electron
63
star
18

proton-mail-settings

React web application to manage ProtonMail settings
TypeScript
52
star
19

ct-monitor

A monitoring tool for certificate transparency of ProtonMail's SSL/TLS certificates
Python
42
star
20

go-srp

Go
38
star
21

pmcrypto

TypeScript
37
star
22

go-proton-api

Proton API library used by Go-based clients and tools
Go
32
star
23

gosop

Stateless CLI for GopenPGP
Go
24
star
24

libsieve-php

libsieve-php is a library to manage and modify sieve (RFC5228) scripts. It contains a parser for the sieve language (including extensions) and a client for the managesieve protocol. It is written entirely in PHP 8+.
PHP
21
star
25

mutex-browser

Acquire a mutex in the browser through IndexedDB or cookies
TypeScript
19
star
26

releaser

A release note generator that reads and parses git commits and retrieves issue links from GitHub.
JavaScript
16
star
27

go-mime

Go
15
star
28

encrypted-search

Encrypted search functionality for the browser
JavaScript
14
star
29

proton-account

Proton account settings
TypeScript
13
star
30

sieve.js

Javascript library to wrap sieve configuration
JavaScript
13
star
31

protoncore_ios

Swift
11
star
32

cpp-openpgp

C++
10
star
33

proton-pack

Command to run a dev-server, build etc. with OpenPGP. On top of webpack.
JavaScript
10
star
34

proton-bundler

CLI tools to bundle Proton web clients for deploys
JavaScript
9
star
35

apple-fusion

fusion is a lightweight and easy-to-use UI testing framework built on top of Apple XCTest that supports testing on iOS and macOS platforms. Developed with readability and reliability in mind.
Swift
9
star
36

bip39

JavaScript implementation of Bitcoin BIP39
TypeScript
8
star
37

componentGenerator

CLI to create new components for the Front-End @ ProtonMail.
JavaScript
7
star
38

interval-tree

Red-black interval tree
TypeScript
7
star
39

php-coding-standard

ProtonLabs Coding Standard for PHP_CodeSniffer (extending PER coding style)
PHP
7
star
40

pm-srp

ProtonMail SRP and auth library
JavaScript
7
star
41

source-map-parser

Command line utility to parse js source maps with with node.js
JavaScript
6
star
42

haproxy-health-check

HAProxy Health Check for EXABGP
Python
6
star
43

pt-formgenerator

Html form generator library
JavaScript
6
star
44

account

JavaScript
6
star
45

go-rfc5322

An RFC5322 address/date parser written in Go
Go
6
star
46

proton-translations

6
star
47

go-ecvrf

Golang implementation of ECVRF-EDWARDS25519-SHA512-TAI, a verifiable random function described in draft-irtf-cfrg-vrf-10.
Go
5
star
48

protonmail.github.io

HTML
5
star
49

therecipe_qt

Go
5
star
50

proton-parking

Gatsby website for parking domains
TypeScript
4
star
51

webcrypto-spec

Specification for extension of webcrypto api
HTML
4
star
52

ios-networking

shared networking framworks
Swift
4
star
53

android-fusion

Android Fusion is a extensible lightweight Android instrumented test framework that combines Espresso, UI Automator and Compose Ui Test into one easy-to-use API with the clear syntax, at the same time keeping the native Android frameworks APIs unchanged.
Kotlin
4
star
54

proton-i18n

CLI to manage translations for client apps
JavaScript
3
star
55

proton-lint

Modern eslint config for a more civilized age
JavaScript
3
star
56

fe-proxy

A simple proxy server that redirects to different urls
JavaScript
3
star
57

Illuminate-Foundation

Illuminate Foundation Mirror
PHP
2
star
58

opendkim

This is a fork of https://sourceforge.net/p/opendkim/git/ci/master/tree/
C
2
star
59

logging

go logging
Go
2
star
60

openpgp-interop-test-analyzer

Python scripts to analyze results from the Openpgp interoperability test suite
Python
2
star
61

danger-random_reviewers

Ruby
1
star
62

u2f

JavaScript
1
star
63

react-storybook

Isolated React components from https://github.com/ProtonMail/react-components
JavaScript
1
star
64

key-transparency-web-client

TypeScript
1
star
65

x509-sign

Simple endpoint to sign ASN1 strings
PHP
1
star
66

openpgp-interop-test-docker

Docker image to run the OpenPGP interoperability test suite
Dockerfile
1
star
67

gomobile-build-tool

Go
1
star
68

therecipe_env_darwin_arm64_513

C++
1
star
69

pm-key-transparency-go-client

Go
1
star
70

proton-mobile-test

HTML
1
star