Debian Codegraph @

launcher/image/testworkloads/customtoken/happypath/main.go

raw
1 // package main is a binary that will print out the validation status of a custom attestation token.
2 package main
3
4 import (
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "net"
11 "net/http"
12 "strings"
13 "time"
14
15 "github.com/golang-jwt/jwt/v4"
16 "github.com/google/go-tpm-tools/verifier/fake"
17 )
18
19 const (
20 socketPath = "/run/container_launcher/teeserver.sock"
21 )
22
23 func getCustomTokenBytes(body string) ([]byte, error) {
24 httpClient := http.Client{
25 Transport: &http.Transport{
26 // Set the DialContext field to a function that creates
27 // a new network connection to a Unix domain socket
28 DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
29 return net.Dial("unix", socketPath)
30 },
31 },
32 }
33
34 // Get the token from the IPC endpoint
35 url := "http://localhost/v1/token"
36
37 resp, err := httpClient.Post(url, "application/json", strings.NewReader(body))
38 if err != nil {
39 return nil, fmt.Errorf("failed to get raw custom token response: %w", err)
40 }
41 tokenbytes, err := io.ReadAll(resp.Body)
42 if err != nil {
43 return nil, fmt.Errorf("failed to read custom token body: %w", err)
44 }
45 resp.Body.Close()
46
47 return tokenbytes, nil
48 }
49
50 func decodeAndValidateToken(tokenBytes []byte, keyFunc func(t *jwt.Token) (any, error)) (*jwt.Token, error) {
51 var err error
52
53 unverifiedClaims := &jwt.RegisteredClaims{}
54 _, _, err = jwt.NewParser().ParseUnverified(string(tokenBytes), unverifiedClaims)
55 if err != nil {
56 return nil, fmt.Errorf("failed to parse claims: %v", err)
57 }
58 now := time.Now()
59 // Add one second for buffer.
60 nbf := unverifiedClaims.NotBefore.Time.Add(time.Second)
61 diff := nbf.Sub(now)
62 ten := 10 * time.Second
63 // Sleep until nbf is valid or max 10 seconds.
64 if diff > 0 {
65 if diff < ten {
66 time.Sleep(diff)
67 } else {
68 time.Sleep(ten)
69 }
70 }
71
72 token, err := jwt.NewParser().Parse(string(tokenBytes), keyFunc)
73
74 fmt.Printf("Token valid: %v", token.Valid)
75 if token.Valid {
76 return token, nil
77 }
78 if ve, ok := err.(*jwt.ValidationError); ok {
79 if ve.Errors&jwt.ValidationErrorMalformed != 0 {
80 return nil, fmt.Errorf("token format invalid. Please contact the Confidential Space team for assistance")
81 }
82 if ve.Errors&(jwt.ValidationErrorNotValidYet) != 0 {
83 // If device time is not synchronized with the Attestation Service you may need to account for that here.
84 return nil, errors.New("token is not active yet")
85 }
86 if ve.Errors&(jwt.ValidationErrorExpired) != 0 {
87 return nil, fmt.Errorf("token is expired")
88 }
89 return nil, fmt.Errorf("unknown validation error: %v", err)
90 }
91
92 return nil, fmt.Errorf("couldn't handle this token or couldn't read a validation error: %v", err)
93 }
94
95 func getTestRSAPublicKey(token *jwt.Token) (any, error) {
96 // Verify the signing method
97 if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
98 return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
99 }
100
101 return fake.TestPublicKey(), nil
102 }
103
104 func main() {
105 // Format token request
106 body := `{
107 "audience": "<YOURAUDIENCE>",
108 "nonces": ["thisIsAcustomNonce", "thisIsAMuchLongerCustomNonceWithPaddingFor74Bytes0000000000000000000000000"],
109 "token_type": "OIDC"
110 }`
111
112 // The following code could be run in a Confidential Space workload container to generate a
113 // custom attestation intended to be sent to a remote party for verification.
114 tokenbytes, err := getCustomTokenBytes(body)
115 if err != nil {
116 fmt.Println(err)
117 return
118 }
119
120 // Method to return a public key used for testing
121 keyFunc := getTestRSAPublicKey
122
123 // The following code could be run by a remote party (not necessarily in a
124 // Confidential Space workload) in order to verify properties of the original
125 // Confidential Space workload that generated the attestation.
126 token, err := decodeAndValidateToken(tokenbytes, keyFunc)
127 if err != nil {
128 fmt.Println(err)
129 return
130 }
131
132 claimsString, err := json.MarshalIndent(token.Claims, "", " ")
133 if err != nil {
134 fmt.Println(err)
135 return
136 }
137
138 fmt.Println(string(claimsString))
139 }