package token import ( "encoding/json" "path/filepath" "strings" "testing" "time" ) func TestIssueAndCheck(t *testing.T) { path := filepath.Join(t.TempDir(), "key") k, err := LoadOrCreate(path, "https://hub.test") if err != nil { t.Fatal(err) } tok, _ := k.Issue("person:1", "t5de-hub", "proxy", time.Minute) c, err := k.Check(tok, "t5de-hub") if err != nil || c.Subject != "person:1" || c.Scope != "proxy" { t.Fatalf("%+v %v", c, err) } if _, err := k.Check(tok, "a-catalog"); err == nil { t.Fatal("accepted for another audience") } // The same key comes back from the file. k2, _ := LoadOrCreate(path, "https://hub.test") if _, err := k2.Check(tok, "t5de-hub"); err != nil { t.Fatal(err) } // Tampering and expiry are caught. parts := strings.Split(tok, ".") forged := parts[0] + "." + b64([]byte(`{"iss":"https://hub.test","sub":"person:2","aud":"t5de-hub","exp":9999999999}`)) + "." + parts[2] if _, err := k.Check(forged, "t5de-hub"); err == nil { t.Fatal("accepted a forged token") } old, _ := k.Issue("person:1", "t5de-hub", "", -time.Second) if _, err := k.Check(old, "t5de-hub"); err == nil { t.Fatal("accepted an expired token") } var jwks struct{ Keys []map[string]string } if json.Unmarshal(k.JWKS(), &jwks) != nil || len(jwks.Keys) != 1 || jwks.Keys[0]["crv"] != "Ed25519" { t.Fatalf("%s", k.JWKS()) } }