Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add replay protection feature #641

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 44 additions & 4 deletions appcheck/appcheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@
package appcheck

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"

Expand Down Expand Up @@ -45,6 +49,8 @@
ErrTokenIssuer = errors.New("token has incorrect issuer")
// ErrTokenSubject is returned when the token subject is empty or missing.
ErrTokenSubject = errors.New("token has empty or missing subject")
// ErrTokenAlreadyConsumed is returned when the token is already consumed
ErrTokenAlreadyConsumed = errors.New("token already consumed")
)

// DecodedAppCheckToken represents a verified App Check token.
Expand All @@ -64,8 +70,9 @@

// Client is the interface for the Firebase App Check service.
type Client struct {
projectID string
jwks *keyfunc.JWKS
projectID string
jwks *keyfunc.JWKS
verifyAppCheckTokenURL string
}

// NewClient creates a new instance of the Firebase App Check Client.
Expand All @@ -83,8 +90,9 @@
}

return &Client{
projectID: conf.ProjectID,
jwks: jwks,
projectID: conf.ProjectID,
jwks: jwks,
verifyAppCheckTokenURL: fmt.Sprintf("%sv1beta/projects/%s:verifyAppCheckToken", appCheckIssuer, conf.ProjectID),
agbaraka marked this conversation as resolved.
Show resolved Hide resolved
}, nil
}

Expand Down Expand Up @@ -166,6 +174,38 @@
return &appCheckToken, nil
}

func (c *Client) VerifyTokenWithReplayProtection(token string) (*DecodedAppCheckToken, error) {

Check failure on line 177 in appcheck/appcheck.go

View workflow job for this annotation

GitHub Actions / Module build (1.20)

exported method Client.VerifyTokenWithReplayProtection should have comment or be unexported

Check failure on line 177 in appcheck/appcheck.go

View workflow job for this annotation

GitHub Actions / Module build (1.21)

exported method Client.VerifyTokenWithReplayProtection should have comment or be unexported

Check failure on line 177 in appcheck/appcheck.go

View workflow job for this annotation

GitHub Actions / Module build (1.22)

exported method Client.VerifyTokenWithReplayProtection should have comment or be unexported
agbaraka marked this conversation as resolved.
Show resolved Hide resolved
decodedAppCheckToken, err := c.VerifyToken(token)

if err != nil {
return nil, fmt.Errorf("failed to verify token: %v", err)
agbaraka marked this conversation as resolved.
Show resolved Hide resolved
}

bodyReader := bytes.NewReader([]byte(fmt.Sprintf(`{"app_check_token":%s}`, token)))

resp, err := http.Post(c.verifyAppCheckTokenURL, "application/json", bodyReader)

if err != nil {
return nil, err
}

defer resp.Body.Close()

var rb struct {
AlreadyConsumed bool `json:"alreadyConsumed"`
}

if err := json.NewDecoder(resp.Body).Decode(&rb); err != nil {
return nil, err
}

if rb.AlreadyConsumed {
return decodedAppCheckToken, ErrTokenAlreadyConsumed
agbaraka marked this conversation as resolved.
Show resolved Hide resolved
}

return decodedAppCheckToken, nil
}

func contains(s []string, str string) bool {
for _, v := range s {
if v == str {
Expand Down
74 changes: 74 additions & 0 deletions appcheck/appcheck_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,80 @@ import (
"github.com/google/go-cmp/cmp"
)

func TestVerifyTokenWithReplayProtection(t *testing.T) {

projectID := "project_id"

ts, err := setupFakeJWKS()
if err != nil {
t.Fatalf("error setting up fake JWKS server: %v", err)
}
defer ts.Close()

privateKey, err := loadPrivateKey()
if err != nil {
t.Fatalf("error loading private key: %v", err)
}

JWKSUrl = ts.URL
mockTime := time.Now()

jwtToken := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.RegisteredClaims{
Issuer: appCheckIssuer,
Audience: jwt.ClaimStrings([]string{"projects/" + projectID}),
agbaraka marked this conversation as resolved.
Show resolved Hide resolved
Subject: "12345678:app:ID",
agbaraka marked this conversation as resolved.
Show resolved Hide resolved
ExpiresAt: jwt.NewNumericDate(mockTime.Add(time.Hour)),
IssuedAt: jwt.NewNumericDate(mockTime),
NotBefore: jwt.NewNumericDate(mockTime.Add(-1 * time.Hour)),
})

// kid matches the key ID in testdata/mock.jwks.json,
// which is the public key matching to the private key
// in testdata/appcheck_pk.pem.
jwtToken.Header["kid"] = "FGQdnRlzAmKyKr6-Hg_kMQrBkj_H6i6ADnBQz4OI6BU"

token, err := jwtToken.SignedString(privateKey)

if err != nil {
t.Fatalf("failed to sign token: %v", err)
}

appCheckVerifyTestsTable := []struct {
label string
mockServerResponse string
expectedError error
}{
{label: "testWhenAlreadyConsumedResponseIsTrue", mockServerResponse: `{"alreadyConsumed": true}`, expectedError: ErrTokenAlreadyConsumed},
{label: "testWhenAlreadyConsumedResponseIsFalse", mockServerResponse: `{"alreadyConsumed": false}`, expectedError: nil},
}

for _, tt := range appCheckVerifyTestsTable {

t.Run(tt.label, func(t *testing.T) {
appCheckVerifyMockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(tt.mockServerResponse))
}))

client, err := NewClient(context.Background(), &internal.AppCheckConfig{
ProjectID: projectID,
})

if err != nil {
t.Fatalf("error creating new client: %v", err)
}

client.verifyAppCheckTokenURL = appCheckVerifyMockServer.URL

_, err = client.VerifyTokenWithReplayProtection(token)

if !errors.Is(err, tt.expectedError) {
t.Errorf("failed to verify token; Expected: %v, but got: %v", tt.expectedError, err)
}
})

}
}

func TestVerifyTokenHasValidClaims(t *testing.T) {
ts, err := setupFakeJWKS()
if err != nil {
Expand Down
Loading