This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
/
verify.go
142 lines (128 loc) · 5.88 KB
/
verify.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package verifyapi implements the exchange of the verification code
// (short term token) for a long term token that can be used to get a
// verification certification to send to the key server.
//
// This is steps 4/5 as specified here:
// https://developers.google.com/android/exposure-notifications/verification-system#flow-diagram
package verifyapi
import (
"errors"
"net/http"
"time"
"github.com/google/exposure-notifications-verification-server/pkg/api"
"github.com/google/exposure-notifications-verification-server/pkg/controller"
"github.com/google/exposure-notifications-verification-server/pkg/database"
"github.com/google/exposure-notifications-verification-server/pkg/jwthelper"
"github.com/google/exposure-notifications-verification-server/pkg/observability"
verifyapi "github.com/google/exposure-notifications-server/pkg/api/v1"
"github.com/dgrijalva/jwt-go"
"go.opencensus.io/stats"
"go.opencensus.io/tag"
)
func (c *Controller) HandleVerify() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
authApp := controller.AuthorizedAppFromContext(ctx)
if authApp == nil {
controller.MissingAuthorizedApp(w, r, c.h)
return
}
// This is a non terminal error, as we're only using the realm for stats.
realm, err := authApp.Realm(c.db)
if err != nil {
c.logger.Errorf("unable to load realm", "error", err)
} else {
ctx, err = tag.New(ctx,
tag.Upsert(observability.RealmTagKey, realm.Name))
if err != nil {
c.logger.Errorw("unable to record metrics for realm", "realmID", realm.ID, "error", err)
}
}
stats.Record(ctx, c.metrics.CodeVerifyAttempts.M(1))
var request api.VerifyCodeRequest
if err := controller.BindJSON(w, r, &request); err != nil {
c.logger.Errorw("bad request", "error", err)
stats.Record(ctx, c.metrics.CodeVerificationError.M(1))
c.h.RenderJSON(w, http.StatusBadRequest, api.Error(err).WithCode(api.ErrUnparsableRequest))
return
}
// Get the signer based on Key configuration.
signer, err := c.kms.NewSigner(ctx, c.config.TokenSigning.ActiveKey())
if err != nil {
c.logger.Errorw("failed to get signer", "error", err)
stats.Record(ctx, c.metrics.CodeVerificationError.M(1))
c.h.RenderJSON(w, http.StatusInternalServerError, api.InternalError())
return
}
// Process and validate the requested acceptable test types.
acceptTypes, err := request.GetAcceptedTestTypes()
if err != nil {
c.logger.Errorf("invalid accept test types", "error", err)
stats.Record(ctx, c.metrics.CodeVerificationError.M(1))
c.h.RenderJSON(w, http.StatusBadRequest, api.Error(err).WithCode(api.ErrInvalidTestType))
return
}
// Exchange the short term verification code for a long term verification token.
// The token can be used to sign TEKs later.
verificationToken, err := c.db.VerifyCodeAndIssueToken(authApp.RealmID, request.VerificationCode, acceptTypes, c.config.VerificationTokenDuration)
if err != nil {
c.logger.Errorw("failed to issue verification token", "error", err)
switch {
case errors.Is(err, database.ErrVerificationCodeExpired):
stats.Record(ctx, c.metrics.CodeVerifyExpired.M(1), c.metrics.CodeVerificationError.M(1))
c.h.RenderJSON(w, http.StatusBadRequest, api.Errorf("verification code expired").WithCode(api.ErrVerifyCodeExpired))
case errors.Is(err, database.ErrVerificationCodeUsed):
stats.Record(ctx, c.metrics.CodeVerifyCodeUsed.M(1), c.metrics.CodeVerificationError.M(1))
c.h.RenderJSON(w, http.StatusBadRequest, api.Errorf("verification code invalid").WithCode(api.ErrVerifyCodeInvalid))
case errors.Is(err, database.ErrVerificationCodeNotFound):
stats.Record(ctx, c.metrics.CodeVerifyInvalid.M(1), c.metrics.CodeVerificationError.M(1))
c.h.RenderJSON(w, http.StatusBadRequest, api.Errorf("verification code invalid").WithCode(api.ErrVerifyCodeInvalid))
case errors.Is(err, database.ErrUnsupportedTestType):
stats.Record(ctx, c.metrics.CodeVerifyInvalid.M(1), c.metrics.CodeVerificationError.M(1))
c.h.RenderJSON(w, http.StatusPreconditionFailed, api.Errorf("verification code has unsupported test type").WithCode(api.ErrUnsupportedTestType))
default:
stats.Record(ctx, c.metrics.CodeVerificationError.M(1))
c.h.RenderJSON(w, http.StatusInternalServerError, api.InternalError())
}
return
}
subject := verificationToken.Subject()
now := time.Now().UTC()
claims := &jwt.StandardClaims{
Audience: c.config.TokenSigning.TokenIssuer,
ExpiresAt: now.Add(c.config.VerificationTokenDuration).Unix(),
Id: verificationToken.TokenID,
IssuedAt: now.Unix(),
Issuer: c.config.TokenSigning.TokenIssuer,
Subject: subject.String(),
}
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
token.Header[verifyapi.KeyIDHeader] = c.config.TokenSigning.ActiveKeyID()
signedJWT, err := jwthelper.SignJWT(token, signer)
if err != nil {
stats.Record(ctx, c.metrics.CodeVerificationError.M(1))
c.logger.Errorw("failed to sign token", "error", err)
c.h.RenderJSON(w, http.StatusBadRequest, api.Error(err).WithCode(api.ErrInternal))
return
}
stats.Record(ctx, c.metrics.CodeVerified.M(1))
c.h.RenderJSON(w, http.StatusOK, api.VerifyCodeResponse{
TestType: verificationToken.TestType,
SymptomDate: verificationToken.FormatSymptomDate(),
VerificationToken: signedJWT,
})
})
}