Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
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
77 changes: 73 additions & 4 deletions appcheck/appcheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package appcheck
import (
"context"
"errors"
"fmt"
"strings"
"time"

Expand All @@ -32,6 +33,8 @@ var JWKSUrl = "https://firebaseappcheck.googleapis.com/v1beta/jwks"

const appCheckIssuer = "https://firebaseappcheck.googleapis.com/"

var verifyTokenURL = "https://firebaseappcheck.googleapis.com/v1beta/projects/%s:verifyAppCheckToken"

var (
// ErrIncorrectAlgorithm is returned when the token is signed with a non-RSA256 algorithm.
ErrIncorrectAlgorithm = errors.New("token has incorrect algorithm")
Expand All @@ -45,6 +48,8 @@ var (
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 +69,9 @@ type DecodedAppCheckToken struct {

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

// NewClient creates a new instance of the Firebase App Check Client.
Expand All @@ -82,9 +88,15 @@ func NewClient(ctx context.Context, conf *internal.AppCheckConfig) (*Client, err
return nil, err
}

hc, _, err := internal.NewHTTPClient(ctx, conf.Opts...)
if err != nil {
return nil, err
}

return &Client{
projectID: conf.ProjectID,
jwks: jwks,
projectID: conf.ProjectID,
jwks: jwks,
httpClient: hc,
}, nil
}

Expand Down Expand Up @@ -166,6 +178,63 @@ func (c *Client) VerifyToken(token string) (*DecodedAppCheckToken, error) {
return &appCheckToken, nil
}

// VerifyOneTimeToken verifies the given App Check token and consumes it, so that it cannot be consumed again.
//
// VerifyOneTimeToken considers an App Check token string to be valid if all the following conditions are met:
// - The token string is a valid RS256 JWT.
// - The JWT contains valid issuer (iss) and audience (aud) claims that match the issuerPrefix
// and projectID of the tokenVerifier.
// - The JWT contains a valid subject (sub) claim.
// - The JWT is not expired, and it has been issued some time in the past.
// - The JWT is signed by a Firebase App Check backend server as determined by the keySource.
//
// If any of the above conditions are not met, an error is returned, regardless whether the token was
// previously consumed or not.
//
// This method currently only supports App Check tokens exchanged from the following attestation
// providers:
//
// - Play Integrity API
// - Apple App Attest
// - Apple DeviceCheck (DCDevice tokens)
// - reCAPTCHA Enterprise
// - reCAPTCHA v3
// - Custom providers
//
// App Check tokens exchanged from debug secrets are also supported. Calling this method on an
// otherwise valid App Check token with an unsupported provider will cause an error to be returned.
//
// If the token was already consumed prior to this call, an error is returned.
func (c *Client) VerifyOneTimeToken(ctx context.Context, token string) (*DecodedAppCheckToken, error) {
decodedAppCheckToken, err := c.VerifyToken(token)

if err != nil {
return nil, err
}

req := &internal.Request{
Method: "POST",
URL: fmt.Sprintf(verifyTokenURL, c.projectID),
Body: internal.NewJSONEntity(map[string]string{
"app_check_token": token,
}),
}

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

if _, err := c.httpClient.DoAndUnmarshal(ctx, req, &resp); err != nil {
return nil, err
}

if resp.AlreadyConsumed {
return nil, ErrTokenAlreadyConsumed
}

return decodedAppCheckToken, nil
}

func contains(s []string, str string) bool {
for _, v := range s {
if v == str {
Expand Down
94 changes: 94 additions & 0 deletions appcheck/appcheck_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package appcheck

import (
"bytes"
"context"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
Expand All @@ -15,8 +17,91 @@
"firebase.google.com/go/v4/internal"
"github.com/golang-jwt/jwt/v4"
"github.com/google/go-cmp/cmp"
"google.golang.org/api/option"
)

func TestVerifyOneTimeToken(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/12345678", "projects/" + projectID}),
Subject: "1:12345678:android:abcdef",
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) {

mockHttpClient := &http.Client{

Check failure on line 74 in appcheck/appcheck_test.go

View workflow job for this annotation

GitHub Actions / Module build (1.23)

var mockHttpClient should be mockHTTPClient

Check failure on line 74 in appcheck/appcheck_test.go

View workflow job for this annotation

GitHub Actions / Module build (1.24)

var mockHttpClient should be mockHTTPClient
Transport: &mockHTTPResponse{
Response: http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString(tt.mockServerResponse)),
},
Err: nil,
},
}

client, err := NewClient(context.Background(), &internal.AppCheckConfig{
ProjectID: projectID,
Opts: []option.ClientOption{
option.WithHTTPClient(mockHttpClient),
},
})

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

_, err = client.VerifyOneTimeToken(context.Background(), token)

if !errors.Is(err, tt.expectedError) {
t.Errorf("Expected error: %v, but got: %v", tt.expectedError, err)
}
})

}
}

func TestVerifyTokenHasValidClaims(t *testing.T) {
ts, err := setupFakeJWKS()
if err != nil {
Expand Down Expand Up @@ -287,3 +372,12 @@
}
return privateKey, nil
}

type mockHTTPResponse struct {
Response http.Response
Err error
}

func (m *mockHTTPResponse) RoundTrip(*http.Request) (*http.Response, error) {
return &m.Response, m.Err
}
1 change: 1 addition & 0 deletions firebase.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ func (a *App) Messaging(ctx context.Context) (*messaging.Client, error) {
func (a *App) AppCheck(ctx context.Context) (*appcheck.Client, error) {
conf := &internal.AppCheckConfig{
ProjectID: a.projectID,
Opts: a.opts,
}
return appcheck.NewClient(ctx, conf)
}
Expand Down
60 changes: 30 additions & 30 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,64 +1,64 @@
module firebase.google.com/go/v4

go 1.23.0
go 1.24.0

require (
cloud.google.com/go/firestore v1.18.0
cloud.google.com/go/storage v1.53.0
cloud.google.com/go/firestore v1.20.0
cloud.google.com/go/storage v1.56.0
github.com/MicahParks/keyfunc v1.9.0
github.com/golang-jwt/jwt/v4 v4.5.2
github.com/google/go-cmp v0.7.0
golang.org/x/oauth2 v0.30.0
google.golang.org/api v0.231.0
google.golang.org/api v0.247.0
google.golang.org/appengine/v2 v2.0.6
)

require (
cel.dev/expr v0.23.1 // indirect
cloud.google.com/go v0.121.0 // indirect
cloud.google.com/go/auth v0.16.1 // indirect
cel.dev/expr v0.24.0 // indirect
cloud.google.com/go v0.121.6 // indirect
cloud.google.com/go/auth v0.16.4 // indirect
cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
cloud.google.com/go/compute/metadata v0.6.0 // indirect
cloud.google.com/go/compute/metadata v0.8.0 // indirect
cloud.google.com/go/iam v1.5.2 // indirect
cloud.google.com/go/longrunning v0.6.7 // indirect
cloud.google.com/go/monitoring v1.24.2 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.27.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.51.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.51.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443 // indirect
github.com/envoyproxy/go-control-plane/envoy v1.32.4 // indirect
github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/go-jose/go-jose/v4 v4.0.5 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/s2a-go v0.1.9 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect
github.com/googleapis/gax-go/v2 v2.14.1 // indirect
github.com/googleapis/gax-go/v2 v2.15.0 // indirect
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect
github.com/spiffe/go-spiffe/v2 v2.5.0 // indirect
github.com/zeebo/errs v1.4.0 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/contrib/detectors/gcp v1.35.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.60.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 // indirect
go.opentelemetry.io/otel v1.35.0 // indirect
go.opentelemetry.io/otel/metric v1.35.0 // indirect
go.opentelemetry.io/otel/sdk v1.35.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.35.0 // indirect
go.opentelemetry.io/otel/trace v1.35.0 // indirect
golang.org/x/crypto v0.40.0 // indirect
golang.org/x/net v0.42.0 // indirect
go.opentelemetry.io/contrib/detectors/gcp v1.36.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect
go.opentelemetry.io/otel v1.36.0 // indirect
go.opentelemetry.io/otel/metric v1.36.0 // indirect
go.opentelemetry.io/otel/sdk v1.36.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.36.0 // indirect
go.opentelemetry.io/otel/trace v1.36.0 // indirect
golang.org/x/crypto v0.41.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/time v0.11.0 // indirect
google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250505200425-f936aa4a68b2 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250505200425-f936aa4a68b2 // indirect
google.golang.org/grpc v1.72.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.12.0 // indirect
google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250818200422-3122310a409c // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250818200422-3122310a409c // indirect
google.golang.org/grpc v1.74.2 // indirect
google.golang.org/protobuf v1.36.7 // indirect
)
Loading
Loading