1// Copyright 2014 The oauth2 Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Package jws provides encoding and decoding utilities for
6// signed JWS messages.
7package jws
8
9import (
10	"bytes"
11	"crypto"
12	"crypto/rand"
13	"crypto/rsa"
14	"crypto/sha256"
15	"encoding/base64"
16	"encoding/json"
17	"errors"
18	"fmt"
19	"strings"
20	"time"
21)
22
23// ClaimSet contains information about the JWT signature including the
24// permissions being requested (scopes), the target of the token, the issuer,
25// the time the token was issued, and the lifetime of the token.
26type ClaimSet struct {
27	Iss   string `json:"iss"`             // email address of the client_id of the application making the access token request
28	Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests
29	Aud   string `json:"aud"`             // descriptor of the intended target of the assertion (Optional).
30	Exp   int64  `json:"exp"`             // the expiration time of the assertion
31	Iat   int64  `json:"iat"`             // the time the assertion was issued.
32	Typ   string `json:"typ,omitempty"`   // token type (Optional).
33
34	// Email for which the application is requesting delegated access (Optional).
35	Sub string `json:"sub,omitempty"`
36
37	// The old name of Sub. Client keeps setting Prn to be
38	// complaint with legacy OAuth 2.0 providers. (Optional)
39	Prn string `json:"prn,omitempty"`
40
41	// See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3
42	// This array is marshalled using custom code (see (c *ClaimSet) encode()).
43	PrivateClaims map[string]interface{} `json:"-"`
44
45	exp time.Time
46	iat time.Time
47}
48
49func (c *ClaimSet) encode() (string, error) {
50	if c.exp.IsZero() || c.iat.IsZero() {
51		// Reverting time back for machines whose time is not perfectly in sync.
52		// If client machine's time is in the future according
53		// to Google servers, an access token will not be issued.
54		now := time.Now().Add(-10 * time.Second)
55		c.iat = now
56		c.exp = now.Add(time.Hour)
57	}
58
59	c.Exp = c.exp.Unix()
60	c.Iat = c.iat.Unix()
61
62	b, err := json.Marshal(c)
63	if err != nil {
64		return "", err
65	}
66
67	if len(c.PrivateClaims) == 0 {
68		return base64Encode(b), nil
69	}
70
71	// Marshal private claim set and then append it to b.
72	prv, err := json.Marshal(c.PrivateClaims)
73	if err != nil {
74		return "", fmt.Errorf("jws: invalid map of private claims %v", c.PrivateClaims)
75	}
76
77	// Concatenate public and private claim JSON objects.
78	if !bytes.HasSuffix(b, []byte{'}'}) {
79		return "", fmt.Errorf("jws: invalid JSON %s", b)
80	}
81	if !bytes.HasPrefix(prv, []byte{'{'}) {
82		return "", fmt.Errorf("jws: invalid JSON %s", prv)
83	}
84	b[len(b)-1] = ','         // Replace closing curly brace with a comma.
85	b = append(b, prv[1:]...) // Append private claims.
86	return base64Encode(b), nil
87}
88
89// Header represents the header for the signed JWS payloads.
90type Header struct {
91	// The algorithm used for signature.
92	Algorithm string `json:"alg"`
93
94	// Represents the token type.
95	Typ string `json:"typ"`
96}
97
98func (h *Header) encode() (string, error) {
99	b, err := json.Marshal(h)
100	if err != nil {
101		return "", err
102	}
103	return base64Encode(b), nil
104}
105
106// Decode decodes a claim set from a JWS payload.
107func Decode(payload string) (*ClaimSet, error) {
108	// decode returned id token to get expiry
109	s := strings.Split(payload, ".")
110	if len(s) < 2 {
111		// TODO(jbd): Provide more context about the error.
112		return nil, errors.New("jws: invalid token received")
113	}
114	decoded, err := base64Decode(s[1])
115	if err != nil {
116		return nil, err
117	}
118	c := &ClaimSet{}
119	err = json.NewDecoder(bytes.NewBuffer(decoded)).Decode(c)
120	return c, err
121}
122
123// Encode encodes a signed JWS with provided header and claim set.
124func Encode(header *Header, c *ClaimSet, signature *rsa.PrivateKey) (string, error) {
125	head, err := header.encode()
126	if err != nil {
127		return "", err
128	}
129	cs, err := c.encode()
130	if err != nil {
131		return "", err
132	}
133	ss := fmt.Sprintf("%s.%s", head, cs)
134	h := sha256.New()
135	h.Write([]byte(ss))
136	b, err := rsa.SignPKCS1v15(rand.Reader, signature, crypto.SHA256, h.Sum(nil))
137	if err != nil {
138		return "", err
139	}
140	sig := base64Encode(b)
141	return fmt.Sprintf("%s.%s", ss, sig), nil
142}
143
144// base64Encode returns and Base64url encoded version of the input string with any
145// trailing "=" stripped.
146func base64Encode(b []byte) string {
147	return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=")
148}
149
150// base64Decode decodes the Base64url encoded string
151func base64Decode(s string) ([]byte, error) {
152	// add back missing padding
153	switch len(s) % 4 {
154	case 2:
155		s += "=="
156	case 3:
157		s += "="
158	}
159	return base64.URLEncoding.DecodeString(s)
160}
161