Debian Codegraph @

token/parse.go

raw symbols SCIP
1 package token
2
3 import (
4 "encoding/json"
5 "regexp"
6 "strings"
7 "time"
8
9 "github.com/pkg/errors"
10 "github.com/smallstep/cli/jose"
11 )
12
13 // Type indicates the token Type.
14 type Type int
15
16 // Token types supported.
17 const (
18 Unknown Type = iota
19 JWK // Smallstep JWK
20 X5C // Smallstep JWK with x5c header
21 OIDC // OpenID Connect
22 GCP // Google Cloud Platform
23 AWS // Amazon Web Services
24 Azure // Microsoft Azure
25 K8sSA // Kubernetes Service Account
26 )
27
28 // JSONWebToken represents a JSON Web Token (as specified in RFC7519). Using the
29 // Parse or ParseInsecure it will contain the payloads supported on step ca.
30 type JSONWebToken struct {
31 *jose.JSONWebToken
32 Payload Payload
33 }
34
35 // Payload represents public claim values (as specified in RFC 7519). In
36 // addition to the standard claims it contains the ones supported in step ca.
37 type Payload struct {
38 jose.Claims
39 SHA string `json:"sha"` // JWK token claims
40 SANs []string `json:"sans"` // ...
41 AtHash string `json:"at_hash"` // OIDC token claims
42 AuthorizedParty string `json:"azp"` // ...
43 Email string `json:"email"`
44 EmailVerified bool `json:"email_verified"`
45 Hd string `json:"hd"`
46 Nonce string `json:"nonce"`
47 AppID string `json:"appid"` // Azure token claims
48 AppIDAcr string `json:"appidacr"` // ...
49 IdentityProvider string `json:"idp"`
50 ObjectID string `json:"oid"`
51 TenantID string `json:"tid"`
52 Version interface{} `json:"ver"`
53 XMSMirID string `json:"xms_mirid"`
54 K8sSANamespace string `json:"kubernetes.io/serviceaccount/namespace,omitempty"`
55 K8sSASecretName string `json:"kubernetes.io/serviceaccount/secret.name,omitempty"`
56 K8sSAServiceAccountName string `json:"kubernetes.io/serviceaccount/service-account.name,omitempty"`
57 K8sSAServiceAccountUID string `json:"kubernetes.io/serviceaccount/service-account.uid,omitempty"`
58 Google *GCPGooglePayload `json:"google"` // GCP token claims
59 Amazon *AWSAmazonPayload `json:"amazon"` // AWS token claims
60 Azure *AzurePayload `json:"azure"` // Azure token claims
61 }
62
63 // Type returns the type of the payload.
64 func (p Payload) Type() Type {
65 switch {
66 case p.Google != nil:
67 return GCP
68 case p.Amazon != nil:
69 return AWS
70 case p.Azure != nil:
71 return Azure
72 case p.Issuer == "kubernetes/serviceaccount":
73 return K8sSA
74 case len(p.SHA) > 0 || len(p.SANs) > 0:
75 return JWK
76 case p.Email != "":
77 return OIDC
78 default:
79 return Unknown
80 }
81 }
82
83 // GCPGooglePayload represents the Google payload in GCP.
84 type GCPGooglePayload struct {
85 ComputeEngine GCPComputeEnginePayload `json:"compute_engine"`
86 }
87
88 // GCPComputeEnginePayload represents the Google ComputeEngine payload in GCP.
89 type GCPComputeEnginePayload struct {
90 InstanceID string `json:"instance_id"`
91 InstanceName string `json:"instance_name"`
92 InstanceCreationTimestamp *jose.NumericDate `json:"instance_creation_timestamp"`
93 ProjectID string `json:"project_id"`
94 ProjectNumber int64 `json:"project_number"`
95 Zone string `json:"zone"`
96 LicenseID []string `json:"license_id"`
97 }
98
99 // AWSAmazonPayload represents the Amazon payload for a AWS token.
100 type AWSAmazonPayload struct {
101 Document []byte `json:"document"`
102 Signature []byte `json:"signature"`
103 InstanceIdentityDocument *AWSInstanceIdentityDocument `json:"-"`
104 }
105
106 // AWSInstanceIdentityDocument is the JSON representation of the instance
107 // identity document.
108 type AWSInstanceIdentityDocument struct {
109 AccountID string `json:"accountId"`
110 Architecture string `json:"architecture"`
111 AvailabilityZone string `json:"availabilityZone"`
112 BillingProducts []string `json:"billingProducts"`
113 DevpayProductCodes []string `json:"devpayProductCodes"`
114 ImageID string `json:"imageId"`
115 InstanceID string `json:"instanceId"`
116 InstanceType string `json:"instanceType"`
117 KernelID string `json:"kernelId"`
118 PendingTime time.Time `json:"pendingTime"`
119 PrivateIP string `json:"privateIp"`
120 RamdiskID string `json:"ramdiskId"`
121 Region string `json:"region"`
122 Version string `json:"version"`
123 }
124
125 // azureXMSMirIDRegExp is the regular expression used to parse the xms_mirid claim.
126 // Using case insensitive as resourceGroups appears as resourcegroups.
127 var azureXMSMirIDRegExp = regexp.MustCompile(`(?i)^/subscriptions/([^/]+)/resourceGroups/([^/]+)/providers/Microsoft.Compute/virtualMachines/([^/]+)$`)
128
129 // AzurePayload contains the information in the xms_mirid claim.
130 type AzurePayload struct {
131 SubscriptionID string
132 ResourceGroup string
133 VirtualMachine string
134 }
135
136 // Parse parses the given token verifying the signature with the key.
137 func Parse(token string, key interface{}) (*JSONWebToken, error) {
138 jwt, err := jose.ParseSigned(token)
139 if err != nil {
140 return nil, errors.Wrap(err, "error parsing token")
141 }
142
143 var p Payload
144 if err := jwt.Claims(key, &p); err != nil {
145 return nil, errors.Wrap(err, "error parsing token claims")
146 }
147
148 return parseResponse(jwt, p)
149 }
150
151 // ParseInsecure parses the given token.
152 func ParseInsecure(token string) (*JSONWebToken, error) {
153 jwt, err := jose.ParseSigned(token)
154 if err != nil {
155 return nil, errors.Wrap(err, "error parsing token")
156 }
157
158 var p Payload
159 if err := jwt.UnsafeClaimsWithoutVerification(&p); err != nil {
160 return nil, errors.Wrap(err, "error parsing token claims")
161 }
162
163 return parseResponse(jwt, p)
164 }
165
166 func parseResponse(jwt *jose.JSONWebToken, p Payload) (*JSONWebToken, error) {
167 switch {
168 case p.Type() == AWS:
169 if err := json.Unmarshal(p.Amazon.Document, &p.Amazon.InstanceIdentityDocument); err != nil {
170 return nil, errors.Wrap(err, "error unmarshaling instance identity document")
171 }
172 case strings.HasPrefix(p.Issuer, "https://sts.windows.net/"):
173 if re := azureXMSMirIDRegExp.FindStringSubmatch(p.XMSMirID); len(re) > 0 {
174 p.Azure = &AzurePayload{
175 SubscriptionID: re[1],
176 ResourceGroup: re[2],
177 VirtualMachine: re[3],
178 }
179 }
180 }
181
182 return &JSONWebToken{
183 JSONWebToken: jwt,
184 Payload: p,
185 }, nil
186 }