build / windows (push) Skipped
build / other_os (push) Skipped
build / mac_amd64 (push) Skipped
build / mac_arm64 (push) Skipped
build / linux (push) Skipped
build / go1.26 (push) Skipped
build / linux_386 (push) Skipped
build / lint (push) Skipped
build / android-all (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/386 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/amd64 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v6 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v7 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm64 (push) Skipped
Build & Push Docker Images / Merge & Push Final Docker Image (push) Waiting for needed jobs
Replace Proton-API-Bridge and go-proton-api with a client in backend/protondrive written against Proton's current Drive API, following the behaviour of Proton's official Drive SDK: - volume-based and v2 routes only - upload block verification, signed manifests and extended attributes - current content encryption (v4 node keys, v6 PKESK, SEIPDv2) - browser (session fork) sign-in, with username and password still supported - the volume's change events, used to keep the metadata cache current and for ChangeNotify, polled at most every 30 s - an in-memory fake Proton server (protontest) so the tests run without an account Uses ProtonMail/gopenpgp/v3 and ProtonMail/go-srp directly; no cgo. Written with heavy AI assistance (Claude Code). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
556 lines
18 KiB
Go
556 lines
18 KiB
Go
package protontest
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/ProtonMail/go-srp"
|
|
"github.com/pquerna/otp/totp"
|
|
"github.com/rclone/rclone/backend/protondrive/api"
|
|
)
|
|
|
|
// signedModulus is a 2048-bit SRP modulus signed by Proton's modulus
|
|
// key, from go-srp's tests.
|
|
const signedModulus = `-----BEGIN PGP SIGNED MESSAGE-----
|
|
Hash: SHA256
|
|
|
|
W2z5HBi8RvsfYzZTS7qBaUxxPhsfHJFZpu3Kd6s1JafNrCCH9rfvPLrfuqocxWPgWDH2R8neK7PkNvjxto9TStuY5z7jAzWRvFWN9cQhAKkdWgy0JY6ywVn22+HFpF4cYesHrqFIKUPDMSSIlWjBVmEJZ/MusD44ZT29xcPrOqeZvwtCffKtGAIjLYPZIEbZKnDM1Dm3q2K/xS5h+xdhjnndhsrkwm9U9oyA2wxzSXFL+pdfj2fOdRwuR5nW0J2NFrq3kJjkRmpO/Genq1UW+TEknIWAb6VzJJJA244K/H8cnSx2+nSNZO3bbo6Ys228ruV9A8m6DhxmS+bihN3ttQ==
|
|
-----BEGIN PGP SIGNATURE-----
|
|
Version: ProtonMail
|
|
Comment: https://protonmail.com
|
|
|
|
wl4EARYIABAFAlwB1j0JEDUFhcTpUY8mAAD8CgEAnsFnF4cF0uSHKkXa1GIa
|
|
GO86yMV4zDZEZcDSJo0fgr8A/AlupGN9EdHlsrZLmTA1vhIx+rOgxdEff28N
|
|
kvNM7qIK
|
|
=q6vu
|
|
-----END PGP SIGNATURE-----`
|
|
|
|
// srpBits is the bit length of the SRP modulus.
|
|
const srpBits = 2048
|
|
|
|
// forkClientID is the client ID rclone's sign-in URL must carry.
|
|
const forkClientID = "external-drive"
|
|
|
|
// User is an account on the fake server.
|
|
type User struct {
|
|
ID string
|
|
Username string
|
|
Password string // login password, checked with SRP
|
|
MailboxPassword string // derives the key password
|
|
KeySalt string // base64 salt of the primary user key's password
|
|
|
|
srv *Server
|
|
srpSalt []byte
|
|
|
|
// Guarded by srv.mu once the user is added.
|
|
keyPassword string
|
|
keys []*userKey // the primary key is last
|
|
addresses []*address // the primary address is first
|
|
drive *drive // nil until the user has a volume
|
|
|
|
verifierOnce sync.Once
|
|
verifier []byte
|
|
verifierErr error
|
|
|
|
// Guarded by srv.mu.
|
|
totpSecret string
|
|
captcha bool
|
|
corruptProof bool
|
|
}
|
|
|
|
// srpVerifier returns the SRP verifier of u's login password, computing
|
|
// it on first use since it costs a bcrypt hash.
|
|
func (u *User) srpVerifier() ([]byte, error) {
|
|
u.verifierOnce.Do(func() {
|
|
var auth *srp.Auth
|
|
auth, u.verifierErr = srp.NewAuthForVerifier([]byte(u.Password), signedModulus, u.srpSalt)
|
|
if u.verifierErr == nil {
|
|
u.verifier, u.verifierErr = auth.GenerateVerifier(srpBits)
|
|
}
|
|
})
|
|
return u.verifier, u.verifierErr
|
|
}
|
|
|
|
// EnableTOTP turns on TOTP two-factor authentication for u and returns
|
|
// the base32 secret to generate codes from.
|
|
func (u *User) EnableTOTP() (secret string) {
|
|
key, err := totp.Generate(totp.GenerateOpts{Issuer: "protontest", AccountName: u.Username})
|
|
if err != nil {
|
|
panic(fmt.Sprintf("protontest: generate TOTP secret: %v", err))
|
|
}
|
|
u.srv.mu.Lock()
|
|
defer u.srv.mu.Unlock()
|
|
u.totpSecret = key.Secret()
|
|
return u.totpSecret
|
|
}
|
|
|
|
// srpLogin is an SRP challenge issued by POST /core/v4/auth/info.
|
|
type srpLogin struct {
|
|
user *User
|
|
server *srp.Server
|
|
}
|
|
|
|
// fork is a session fork requested by GET /auth/v4/sessions/forks.
|
|
type fork struct {
|
|
userCode string
|
|
key []byte // encryption key from the sign-in URL, once approved
|
|
approved *session // child session, once approved
|
|
}
|
|
|
|
// Session holds the tokens of a signed in session.
|
|
type Session struct {
|
|
UID string
|
|
AccessToken string
|
|
RefreshToken string
|
|
}
|
|
|
|
// session is the server side state of a Session.
|
|
type session struct {
|
|
Session
|
|
user *User
|
|
expired bool // access token no longer accepted
|
|
locked bool // waiting for the second factor
|
|
}
|
|
|
|
// randomBytes returns n random bytes.
|
|
func randomBytes(n int) []byte {
|
|
b := make([]byte, n)
|
|
_, _ = rand.Read(b)
|
|
return b
|
|
}
|
|
|
|
// randomID returns a random hex string.
|
|
func randomID() string {
|
|
return hex.EncodeToString(randomBytes(16))
|
|
}
|
|
|
|
// registerAuth registers the session routes.
|
|
func (s *Server) registerAuth() {
|
|
s.handle("POST", "/auth/v4/refresh", s.handleRefresh)
|
|
s.handle("POST", "/core/v4/auth/info", s.handleAuthInfo)
|
|
s.handle("POST", "/core/v4/auth", s.handleLogin)
|
|
s.handleSession("POST", "/core/v4/auth/2fa", s.handle2FA)
|
|
s.handleSession("DELETE", "/core/v4/auth", s.handleLogout)
|
|
s.handleAuth("GET", "/core/v4/keys/salts", s.handleKeySalts)
|
|
s.handle("GET", "/auth/v4/sessions/forks", s.handleForkInit)
|
|
s.handle("GET", "/auth/v4/sessions/forks/{selector}", s.handleForkStatus)
|
|
s.handleAuth("GET", "/tests/auth", func(w http.ResponseWriter, r *http.Request, u *User) {
|
|
writeJSON(w, http.StatusOK, map[string]any{"Code": api.CodeOK, "UserID": u.ID})
|
|
})
|
|
s.handleAuth("POST", "/tests/echo", func(w http.ResponseWriter, r *http.Request, u *User) {
|
|
var body struct{ Echo string }
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: "+err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"Code": api.CodeOK, "Echo": body.Echo})
|
|
})
|
|
}
|
|
|
|
// AddUser creates an account whose mailbox password is its password.
|
|
func (s *Server) AddUser(username, password string) *User {
|
|
return s.AddTwoPasswordUser(username, password, password)
|
|
}
|
|
|
|
// AddTwoPasswordUser creates an account which signs in with password
|
|
// and unlocks its keys with mailboxPassword.
|
|
//
|
|
// The account has a user key and one address, username itself if it
|
|
// contains "@" or else username@proton.test, with an address key. Its
|
|
// drive has a volume, a main share and an empty root folder.
|
|
func (s *Server) AddTwoPasswordUser(username, password, mailboxPassword string) *User {
|
|
u := newUser(s, username, password, mailboxPassword)
|
|
u.drive = s.newDrive(u.addresses[0])
|
|
s.addUser(u)
|
|
return u
|
|
}
|
|
|
|
// AddUserWithoutDrive creates an account like AddUser but without a
|
|
// volume, as a brand-new Proton account is: its my-files route answers
|
|
// HTTP 422 code 2501 until a client creates the volume.
|
|
func (s *Server) AddUserWithoutDrive(username, password string) *User {
|
|
u := newUser(s, username, password, password)
|
|
s.addUser(u)
|
|
return u
|
|
}
|
|
|
|
// newUser returns an account with a user key and one address, not yet
|
|
// added to s.
|
|
func newUser(s *Server, username, password, mailboxPassword string) *User {
|
|
u := &User{
|
|
ID: randomID(),
|
|
Username: username,
|
|
Password: password,
|
|
MailboxPassword: mailboxPassword,
|
|
srv: s,
|
|
srpSalt: randomBytes(10),
|
|
}
|
|
key := newUserKey(u)
|
|
u.keys = []*userKey{key}
|
|
u.KeySalt, u.keyPassword = key.salt, key.keyPassword
|
|
email := username
|
|
if !strings.Contains(email, "@") {
|
|
email += "@proton.test"
|
|
}
|
|
u.addresses = []*address{newAddress(email, key)}
|
|
return u
|
|
}
|
|
|
|
// addUser adds u to s.
|
|
func (s *Server) addUser(u *User) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.users[u.Username] = u
|
|
}
|
|
|
|
// RequireCaptcha makes password sign-in for u fail with HTTP 422 code
|
|
// 9001, as when Proton asks for human verification.
|
|
func (s *Server) RequireCaptcha(u *User) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
u.captcha = true
|
|
}
|
|
|
|
// CorruptServerProof makes password sign-in for u return a server
|
|
// proof with one byte changed, as an impostor server would.
|
|
func (s *Server) CorruptServerProof(u *User) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
u.corruptProof = true
|
|
}
|
|
|
|
// NewSession signs u in and returns the new session's tokens.
|
|
func (s *Server) NewSession(u *User) Session {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.newSessionLocked(u, false).Session
|
|
}
|
|
|
|
// newSessionLocked creates a session for u. s.mu must be held.
|
|
func (s *Server) newSessionLocked(u *User, locked bool) *session {
|
|
sess := &session{
|
|
Session: Session{UID: randomID(), AccessToken: s.newSecretLocked(SessionToken), RefreshToken: s.newSecretLocked(SessionToken)},
|
|
user: u,
|
|
locked: locked,
|
|
}
|
|
s.sessions[sess.UID] = sess
|
|
return sess
|
|
}
|
|
|
|
// ApproveFork completes the session fork whose sign-in URL is
|
|
// signInURL as if u had signed in on Proton's page: the next poll of
|
|
// the fork returns a new session for u and u's key password encrypted
|
|
// with the key from the URL.
|
|
func (s *Server) ApproveFork(signInURL string, u *User) error {
|
|
parsed, err := url.Parse(signInURL)
|
|
if err != nil {
|
|
return fmt.Errorf("protontest: parse sign-in URL: %w", err)
|
|
}
|
|
payload, ok := strings.CutPrefix(parsed.Fragment, "payload=")
|
|
parts := strings.Split(payload, ":")
|
|
if !ok || len(parts) != 4 || parts[0] != "0" || parts[3] != forkClientID {
|
|
return fmt.Errorf("protontest: bad sign-in URL payload %q", payload)
|
|
}
|
|
key, err := base64.StdEncoding.DecodeString(parts[2])
|
|
if err != nil || len(key) != 32 {
|
|
return fmt.Errorf("protontest: bad key in sign-in URL payload %q", payload)
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for _, f := range s.forks {
|
|
if f.userCode == parts[1] {
|
|
f.key = key
|
|
f.approved = s.newSessionLocked(u, false)
|
|
return nil
|
|
}
|
|
}
|
|
return fmt.Errorf("protontest: no fork with user code %q", parts[1])
|
|
}
|
|
|
|
// ExpireAccessToken makes the access token of session uid return 401
|
|
// until the session is refreshed.
|
|
func (s *Server) ExpireAccessToken(uid string) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if sess := s.sessions[uid]; sess != nil {
|
|
sess.expired = true
|
|
}
|
|
}
|
|
|
|
// RevokeSession ends session uid, so neither its access token nor its
|
|
// refresh token is accepted.
|
|
func (s *Server) RevokeSession(uid string) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
delete(s.sessions, uid)
|
|
}
|
|
|
|
// handleAuth registers h for an authenticated route. Requests without
|
|
// a valid x-pm-uid and bearer access token get HTTP 401, and requests
|
|
// from a session waiting for its second factor get HTTP 403.
|
|
func (s *Server) handleAuth(method, pattern string, h func(w http.ResponseWriter, r *http.Request, u *User)) {
|
|
s.handleSession(method, pattern, func(w http.ResponseWriter, r *http.Request, sess *session) {
|
|
s.mu.Lock()
|
|
locked := sess.locked
|
|
s.mu.Unlock()
|
|
if locked {
|
|
writeError(w, http.StatusForbidden, 0, "protontest: second factor required")
|
|
return
|
|
}
|
|
h(w, r, sess.user)
|
|
})
|
|
}
|
|
|
|
// handleSession registers h for a route which needs a session, which
|
|
// may be waiting for its second factor. Requests without a valid
|
|
// x-pm-uid and bearer access token get HTTP 401.
|
|
func (s *Server) handleSession(method, pattern string, h func(w http.ResponseWriter, r *http.Request, sess *session)) {
|
|
s.handle(method, pattern, func(w http.ResponseWriter, r *http.Request) {
|
|
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
|
s.mu.Lock()
|
|
sess := s.sessions[r.Header.Get("x-pm-uid")]
|
|
valid := ok && sess != nil && !sess.expired && sess.AccessToken == token
|
|
s.mu.Unlock()
|
|
if !valid {
|
|
writeError(w, http.StatusUnauthorized, 401, "protontest: invalid access token")
|
|
return
|
|
}
|
|
h(w, r, sess)
|
|
})
|
|
}
|
|
|
|
// handleRefresh rotates the tokens of the session named by x-pm-uid.
|
|
// Refresh tokens are single use.
|
|
func (s *Server) handleRefresh(w http.ResponseWriter, r *http.Request) {
|
|
var req api.AuthRefreshRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ResponseType != "token" || req.GrantType != "refresh_token" {
|
|
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad refresh request")
|
|
return
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
sess := s.sessions[r.Header.Get("x-pm-uid")]
|
|
if sess == nil || req.RefreshToken == "" || sess.RefreshToken != req.RefreshToken {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeRefreshTokenInvalid, "protontest: invalid refresh token")
|
|
return
|
|
}
|
|
sess.AccessToken = s.newSecretLocked(SessionToken)
|
|
sess.RefreshToken = s.newSecretLocked(SessionToken)
|
|
sess.expired = false
|
|
writeJSON(w, http.StatusOK, &api.AuthRefreshResponse{
|
|
Code: api.CodeOK,
|
|
UID: sess.UID,
|
|
AccessToken: sess.AccessToken,
|
|
RefreshToken: sess.RefreshToken,
|
|
})
|
|
}
|
|
|
|
// handleAuthInfo issues an SRP challenge for the user named in the
|
|
// request.
|
|
func (s *Server) handleAuthInfo(w http.ResponseWriter, r *http.Request) {
|
|
var req api.AuthInfoRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Intent != "Proton" {
|
|
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad auth info request")
|
|
return
|
|
}
|
|
s.mu.Lock()
|
|
u := s.users[req.Username]
|
|
s.mu.Unlock()
|
|
if u == nil {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodePasswordWrong, "protontest: unknown user")
|
|
return
|
|
}
|
|
verifier, err := u.srpVerifier()
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, 0, "protontest: SRP verifier: "+err.Error())
|
|
return
|
|
}
|
|
server, err := srp.NewServerFromSigned(signedModulus, verifier, srpBits)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, 0, "protontest: SRP server: "+err.Error())
|
|
return
|
|
}
|
|
challenge, err := server.GenerateChallenge()
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, 0, "protontest: SRP challenge: "+err.Error())
|
|
return
|
|
}
|
|
srpSession := randomID()
|
|
s.mu.Lock()
|
|
s.srp[srpSession] = &srpLogin{user: u, server: server}
|
|
s.mu.Unlock()
|
|
writeJSON(w, http.StatusOK, &api.AuthInfoResponse{
|
|
Code: api.CodeOK,
|
|
Version: 4,
|
|
Modulus: signedModulus,
|
|
ServerEphemeral: base64.StdEncoding.EncodeToString(challenge),
|
|
Salt: base64.StdEncoding.EncodeToString(u.srpSalt),
|
|
SRPSession: srpSession,
|
|
Username: u.Username,
|
|
})
|
|
}
|
|
|
|
// handleLogin checks the SRP proof for a challenge and creates a
|
|
// session, locked until the second factor if the user has TOTP.
|
|
// Challenges are single use.
|
|
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|
var req api.AuthRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad auth request")
|
|
return
|
|
}
|
|
ephemeral, err1 := base64.StdEncoding.DecodeString(req.ClientEphemeral)
|
|
proof, err2 := base64.StdEncoding.DecodeString(req.ClientProof)
|
|
if err := errors.Join(err1, err2); err != nil {
|
|
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad auth request: "+err.Error())
|
|
return
|
|
}
|
|
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
login := s.srp[req.SRPSession]
|
|
delete(s.srp, req.SRPSession)
|
|
if login == nil || login.user.Username != req.Username {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: unknown SRP session")
|
|
return
|
|
}
|
|
u := login.user
|
|
if u.captcha {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeHumanVerification, "protontest: human verification required")
|
|
return
|
|
}
|
|
serverProof, err := login.server.VerifyProofs(ephemeral, proof)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodePasswordWrong, "protontest: incorrect login credentials")
|
|
return
|
|
}
|
|
if u.corruptProof {
|
|
serverProof[0] ^= 1
|
|
}
|
|
resp := &api.AuthResponse{
|
|
Code: api.CodeOK,
|
|
UserID: u.ID,
|
|
TokenType: "Bearer",
|
|
ServerProof: base64.StdEncoding.EncodeToString(serverProof),
|
|
Scopes: []string{"full"},
|
|
PasswordMode: api.PasswordModeOne,
|
|
}
|
|
if u.MailboxPassword != u.Password {
|
|
resp.PasswordMode = api.PasswordModeTwo
|
|
}
|
|
if u.totpSecret != "" {
|
|
resp.TwoFA.Enabled = api.TwoFATOTP
|
|
resp.Scopes = []string{"twofactor"}
|
|
}
|
|
sess := s.newSessionLocked(u, u.totpSecret != "")
|
|
resp.UID, resp.AccessToken, resp.RefreshToken = sess.UID, sess.AccessToken, sess.RefreshToken
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
// handle2FA unlocks a session with a TOTP code.
|
|
func (s *Server) handle2FA(w http.ResponseWriter, r *http.Request, sess *session) {
|
|
var req api.Auth2FARequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad 2FA request")
|
|
return
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
secret := sess.user.totpSecret
|
|
if secret == "" || !totp.Validate(req.TwoFactorCode, secret) {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: incorrect 2FA code")
|
|
return
|
|
}
|
|
sess.locked = false
|
|
writeJSON(w, http.StatusOK, map[string]any{"Code": api.CodeOK, "Scopes": []string{"full"}})
|
|
}
|
|
|
|
// handleLogout ends the session.
|
|
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request, sess *session) {
|
|
s.mu.Lock()
|
|
delete(s.sessions, sess.UID)
|
|
s.mu.Unlock()
|
|
writeJSON(w, http.StatusOK, map[string]any{"Code": api.CodeOK})
|
|
}
|
|
|
|
// handleKeySalts returns the password salt of each user key.
|
|
func (s *Server) handleKeySalts(w http.ResponseWriter, r *http.Request, u *User) {
|
|
resp := &api.KeySaltsResponse{Code: api.CodeOK}
|
|
s.mu.Lock()
|
|
for _, key := range u.keys {
|
|
resp.KeySalts = append(resp.KeySalts, api.KeySalt{ID: key.id, KeySalt: key.salt})
|
|
}
|
|
s.mu.Unlock()
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
// handleForkInit starts a session fork for a client to sign in with.
|
|
func (s *Server) handleForkInit(w http.ResponseWriter, r *http.Request) {
|
|
f := &fork{userCode: strings.ToUpper(hex.EncodeToString(randomBytes(4)))}
|
|
s.mu.Lock()
|
|
selector := s.newSecretLocked(ForkSelector)
|
|
s.forks[selector] = f
|
|
s.mu.Unlock()
|
|
writeJSON(w, http.StatusOK, &api.ForkInitResponse{Code: api.CodeOK, Selector: selector, UserCode: f.userCode})
|
|
}
|
|
|
|
// handleForkStatus returns the child session of an approved fork, once,
|
|
// or HTTP 422 while the fork is waiting for approval.
|
|
func (s *Server) handleForkStatus(w http.ResponseWriter, r *http.Request) {
|
|
selector := r.PathValue("selector")
|
|
s.mu.Lock()
|
|
f := s.forks[selector]
|
|
if f == nil || f.approved == nil {
|
|
s.mu.Unlock()
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: fork not ready")
|
|
return
|
|
}
|
|
delete(s.forks, selector)
|
|
sess := f.approved.Session
|
|
user := f.approved.user
|
|
s.mu.Unlock()
|
|
|
|
payload, err := sealForkPayload(f.key, user.KeyPassword())
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, 0, "protontest: fork payload: "+err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, &api.ForkStatusResponse{
|
|
Code: api.CodeOK,
|
|
Payload: payload,
|
|
UID: sess.UID,
|
|
AccessToken: sess.AccessToken,
|
|
RefreshToken: sess.RefreshToken,
|
|
})
|
|
}
|
|
|
|
// sealForkPayload encrypts keyPassword for a fork as Proton's sign-in
|
|
// page does: base64 of nonce, AES-256-GCM ciphertext and tag, with
|
|
// additional data "fork".
|
|
func sealForkPayload(key []byte, keyPassword string) (string, error) {
|
|
plain, err := json.Marshal(map[string]string{"keyPassword": keyPassword})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
nonce := randomBytes(gcm.NonceSize())
|
|
return base64.StdEncoding.EncodeToString(gcm.Seal(nonce, nonce, plain, []byte("fork"))), nil
|
|
}
|