| 1 | package httpsig |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto" |
| 6 | "crypto/rand" |
| 7 | "crypto/rsa" |
| 8 | "crypto/sha256" |
| 9 | "crypto/x509" |
| 10 | "encoding/asn1" |
| 11 | "encoding/base64" |
| 12 | "encoding/pem" |
| 13 | "fmt" |
| 14 | "io/ioutil" |
| 15 | "net/http" |
| 16 | "net/http/httptest" |
| 17 | "strconv" |
| 18 | "strings" |
| 19 | "testing" |
| 20 | |
| 21 | "golang.org/x/crypto/ed25519" |
| 22 | ) |
| 23 | |
| 24 | const ( |
| 25 | testUrl = "foo.net/bar/baz?q=test&r=ok" |
| 26 | testUrlPath = "bar/baz" |
| 27 | testDate = "Tue, 07 Jun 2014 20:51:35 GMT" |
| 28 | testDigest = "SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=" |
| 29 | testMethod = "GET" |
| 30 | ) |
| 31 | |
| 32 | type httpsigTest struct { |
| 33 | name string |
| 34 | prefs []Algorithm |
| 35 | digestAlg DigestAlgorithm |
| 36 | headers []string |
| 37 | body []byte |
| 38 | scheme SignatureScheme |
| 39 | privKey crypto.PrivateKey |
| 40 | pubKey crypto.PublicKey |
| 41 | pubKeyId string |
| 42 | expectedSignatureAlgorithm string |
| 43 | expectedAlgorithm Algorithm |
| 44 | expectErrorSigningResponse bool |
| 45 | expectRequestPath bool |
| 46 | expectedDigest string |
| 47 | } |
| 48 | |
| 49 | type ed25519PrivKey struct { |
| 50 | Version int |
| 51 | ObjectIdentifier struct { |
| 52 | ObjectIdentifier asn1.ObjectIdentifier |
| 53 | } |
| 54 | PrivateKey []byte |
| 55 | } |
| 56 | |
| 57 | type ed25519PubKey struct { |
| 58 | OBjectIdentifier struct { |
| 59 | ObjectIdentifier asn1.ObjectIdentifier |
| 60 | } |
| 61 | PublicKey asn1.BitString |
| 62 | } |
| 63 | |
| 64 | var ( |
| 65 | privKey *rsa.PrivateKey |
| 66 | macKey []byte |
| 67 | tests []httpsigTest |
| 68 | testSpecRSAPrivateKey *rsa.PrivateKey |
| 69 | testSpecRSAPublicKey *rsa.PublicKey |
| 70 | testEd25519PrivateKey ed25519.PrivateKey |
| 71 | testEd25519PublicKey ed25519.PublicKey |
| 72 | ) |
| 73 | |
| 74 | func init() { |
| 75 | var err error |
| 76 | privKey, err = rsa.GenerateKey(rand.Reader, 2048) |
| 77 | if err != nil { |
| 78 | panic(err) |
| 79 | } |
| 80 | pubEd25519Key, privEd25519Key, err := ed25519.GenerateKey(rand.Reader) |
| 81 | if err != nil { |
| 82 | panic(err) |
| 83 | } |
| 84 | macKey = make([]byte, 128) |
| 85 | err = readFullFromCrypto(macKey) |
| 86 | if err != nil { |
| 87 | panic(err) |
| 88 | } |
| 89 | tests = []httpsigTest{ |
| 90 | { |
| 91 | name: "rsa signature", |
| 92 | prefs: []Algorithm{RSA_SHA512}, |
| 93 | digestAlg: DigestSha256, |
| 94 | headers: []string{"Date", "Digest"}, |
| 95 | scheme: Signature, |
| 96 | privKey: privKey, |
| 97 | pubKey: privKey.Public(), |
| 98 | pubKeyId: "pubKeyId", |
| 99 | expectedAlgorithm: RSA_SHA512, |
| 100 | expectedSignatureAlgorithm: "hs2019", |
| 101 | }, |
| 102 | { |
| 103 | name: "ed25519 signature", |
| 104 | prefs: []Algorithm{ED25519}, |
| 105 | digestAlg: DigestSha512, |
| 106 | headers: []string{"Date", "Digest"}, |
| 107 | scheme: Signature, |
| 108 | privKey: privEd25519Key, |
| 109 | pubKey: pubEd25519Key, |
| 110 | pubKeyId: "pubKeyId", |
| 111 | expectedAlgorithm: ED25519, |
| 112 | expectedSignatureAlgorithm: "hs2019", |
| 113 | }, |
| 114 | { |
| 115 | name: "digest on rsa signature", |
| 116 | prefs: []Algorithm{RSA_SHA512}, |
| 117 | digestAlg: DigestSha256, |
| 118 | headers: []string{"Date", "Digest"}, |
| 119 | body: []byte("Last night as I lay dreaming This strangest kind of feeling Revealed its secret meaning And now I know..."), |
| 120 | scheme: Signature, |
| 121 | privKey: privKey, |
| 122 | pubKey: privKey.Public(), |
| 123 | pubKeyId: "pubKeyId", |
| 124 | expectedAlgorithm: RSA_SHA512, |
| 125 | expectedSignatureAlgorithm: "hs2019", |
| 126 | expectedDigest: "SHA-256=07PJQngqg8+BlomdI6zM7ieOxhINWI+iivJxBDSm3Dg=", |
| 127 | }, |
| 128 | { |
| 129 | name: "digest on ed25519 signature", |
| 130 | prefs: []Algorithm{ED25519}, |
| 131 | digestAlg: DigestSha256, |
| 132 | headers: []string{"Date", "Digest"}, |
| 133 | body: []byte("Last night as I lay dreaming This strangest kind of feeling Revealed its secret meaning And now I know..."), |
| 134 | scheme: Signature, |
| 135 | privKey: privEd25519Key, |
| 136 | pubKey: pubEd25519Key, |
| 137 | pubKeyId: "pubKeyId", |
| 138 | expectedAlgorithm: ED25519, |
| 139 | expectedSignatureAlgorithm: "hs2019", |
| 140 | expectedDigest: "SHA-256=07PJQngqg8+BlomdI6zM7ieOxhINWI+iivJxBDSm3Dg=", |
| 141 | }, |
| 142 | { |
| 143 | name: "hmac signature", |
| 144 | prefs: []Algorithm{HMAC_SHA256}, |
| 145 | digestAlg: DigestSha256, |
| 146 | headers: []string{"Date", "Digest"}, |
| 147 | scheme: Signature, |
| 148 | privKey: macKey, |
| 149 | pubKey: macKey, |
| 150 | pubKeyId: "pubKeyId", |
| 151 | expectedAlgorithm: HMAC_SHA256, |
| 152 | expectedSignatureAlgorithm: "hs2019", |
| 153 | }, |
| 154 | { |
| 155 | name: "digest on hmac signature", |
| 156 | prefs: []Algorithm{HMAC_SHA256}, |
| 157 | digestAlg: DigestSha256, |
| 158 | headers: []string{"Date", "Digest"}, |
| 159 | body: []byte("I've never ever been to paradise I've never ever seen no angel's eyes You'll never ever let this magic die No matter where you are, you are my lucky star."), |
| 160 | scheme: Signature, |
| 161 | privKey: macKey, |
| 162 | pubKey: macKey, |
| 163 | pubKeyId: "pubKeyId", |
| 164 | expectedAlgorithm: HMAC_SHA256, |
| 165 | expectedSignatureAlgorithm: "hs2019", |
| 166 | expectedDigest: "SHA-256=d0JoDjbDZRZF7/gUdgrazZCdKCJ9z9uUcMd6n1YKWRU=", |
| 167 | }, |
| 168 | { |
| 169 | name: "rsa authorization", |
| 170 | prefs: []Algorithm{RSA_SHA512}, |
| 171 | digestAlg: DigestSha256, |
| 172 | headers: []string{"Date", "Digest"}, |
| 173 | scheme: Authorization, |
| 174 | privKey: privKey, |
| 175 | pubKey: privKey.Public(), |
| 176 | pubKeyId: "pubKeyId", |
| 177 | expectedAlgorithm: RSA_SHA512, |
| 178 | expectedSignatureAlgorithm: "hs2019", |
| 179 | }, |
| 180 | { |
| 181 | name: "ed25519 authorization", |
| 182 | prefs: []Algorithm{ED25519}, |
| 183 | digestAlg: DigestSha256, |
| 184 | headers: []string{"Date", "Digest"}, |
| 185 | scheme: Authorization, |
| 186 | privKey: privEd25519Key, |
| 187 | pubKey: pubEd25519Key, |
| 188 | pubKeyId: "pubKeyId", |
| 189 | expectedAlgorithm: ED25519, |
| 190 | expectedSignatureAlgorithm: "hs2019", |
| 191 | }, |
| 192 | { |
| 193 | name: "hmac authorization", |
| 194 | prefs: []Algorithm{HMAC_SHA256}, |
| 195 | digestAlg: DigestSha256, |
| 196 | headers: []string{"Date", "Digest"}, |
| 197 | scheme: Authorization, |
| 198 | privKey: macKey, |
| 199 | pubKey: macKey, |
| 200 | pubKeyId: "pubKeyId", |
| 201 | expectedAlgorithm: HMAC_SHA256, |
| 202 | expectedSignatureAlgorithm: "hs2019", |
| 203 | }, |
| 204 | { |
| 205 | name: "default algo", |
| 206 | digestAlg: DigestSha256, |
| 207 | headers: []string{"Date", "Digest"}, |
| 208 | scheme: Signature, |
| 209 | privKey: privKey, |
| 210 | pubKey: privKey.Public(), |
| 211 | pubKeyId: "pubKeyId", |
| 212 | expectedAlgorithm: RSA_SHA256, |
| 213 | expectedSignatureAlgorithm: "hs2019", |
| 214 | }, |
| 215 | { |
| 216 | name: "default headers", |
| 217 | prefs: []Algorithm{RSA_SHA512}, |
| 218 | digestAlg: DigestSha256, |
| 219 | scheme: Signature, |
| 220 | privKey: privKey, |
| 221 | pubKey: privKey.Public(), |
| 222 | pubKeyId: "pubKeyId", |
| 223 | expectedAlgorithm: RSA_SHA512, |
| 224 | expectedSignatureAlgorithm: "hs2019", |
| 225 | }, |
| 226 | { |
| 227 | name: "different pub key id", |
| 228 | prefs: []Algorithm{RSA_SHA512}, |
| 229 | digestAlg: DigestSha256, |
| 230 | headers: []string{"Date", "Digest"}, |
| 231 | scheme: Signature, |
| 232 | privKey: privKey, |
| 233 | pubKey: privKey.Public(), |
| 234 | pubKeyId: "i write code that sucks", |
| 235 | expectedAlgorithm: RSA_SHA512, |
| 236 | expectedSignatureAlgorithm: "hs2019", |
| 237 | }, |
| 238 | { |
| 239 | name: "with request target", |
| 240 | prefs: []Algorithm{RSA_SHA512}, |
| 241 | digestAlg: DigestSha256, |
| 242 | headers: []string{"Date", "Digest", RequestTarget}, |
| 243 | scheme: Signature, |
| 244 | privKey: privKey, |
| 245 | pubKey: privKey.Public(), |
| 246 | pubKeyId: "pubKeyId", |
| 247 | expectedAlgorithm: RSA_SHA512, |
| 248 | expectedSignatureAlgorithm: "hs2019", |
| 249 | expectErrorSigningResponse: true, |
| 250 | expectRequestPath: true, |
| 251 | }, |
| 252 | } |
| 253 | |
| 254 | testSpecRSAPrivateKey, err = loadPrivateKey([]byte(testSpecPrivateKeyPEM)) |
| 255 | if err != nil { |
| 256 | panic(err) |
| 257 | } |
| 258 | |
| 259 | testSpecRSAPublicKey, err = loadPublicKey([]byte(testSpecPublicKeyPEM)) |
| 260 | if err != nil { |
| 261 | panic(err) |
| 262 | } |
| 263 | |
| 264 | testEd25519PrivateKey, err = loadEd25519PrivateKey([]byte(testEd25519PrivateKeyPEM)) |
| 265 | if err != nil { |
| 266 | panic(err) |
| 267 | } |
| 268 | |
| 269 | testEd25519PublicKey, err = loadEd25519PublicKey([]byte(testEd25519PublicKeyPEM)) |
| 270 | if err != nil { |
| 271 | panic(err) |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | func toSignatureParameter(k, v string) string { |
| 276 | return fmt.Sprintf("%s%s%s%s%s", k, parameterKVSeparater, parameterValueDelimiter, v, parameterValueDelimiter) |
| 277 | } |
| 278 | |
| 279 | func toHeaderSignatureParameters(k string, vals []string) string { |
| 280 | if len(vals) == 0 { |
| 281 | vals = defaultHeaders |
| 282 | } |
| 283 | v := strings.Join(vals, headerParameterValueDelim) |
| 284 | k = strings.ToLower(k) |
| 285 | v = strings.ToLower(v) |
| 286 | return fmt.Sprintf("%s%s%s%s%s", k, parameterKVSeparater, parameterValueDelimiter, v, parameterValueDelimiter) |
| 287 | } |
| 288 | |
| 289 | func TestSignerRequest(t *testing.T) { |
| 290 | testFn := func(t *testing.T, test httpsigTest) { |
| 291 | s, a, err := NewSigner(test.prefs, test.digestAlg, test.headers, test.scheme, 0) |
| 292 | if err != nil { |
| 293 | t.Fatalf("%s", err) |
| 294 | } |
| 295 | if a != test.expectedAlgorithm { |
| 296 | t.Fatalf("got %s, want %s", a, test.expectedAlgorithm) |
| 297 | } |
| 298 | // Test request signing |
| 299 | req, err := http.NewRequest(testMethod, testUrl, nil) |
| 300 | if err != nil { |
| 301 | t.Fatalf("%s", err) |
| 302 | } |
| 303 | req.Header.Set("Date", testDate) |
| 304 | if test.body == nil { |
| 305 | req.Header.Set("Digest", testDigest) |
| 306 | } |
| 307 | err = s.SignRequest(test.privKey, test.pubKeyId, req, test.body) |
| 308 | if err != nil { |
| 309 | t.Fatalf("%s", err) |
| 310 | } |
| 311 | vals, ok := req.Header[string(test.scheme)] |
| 312 | if !ok { |
| 313 | t.Fatalf("not in header %s", test.scheme) |
| 314 | } |
| 315 | if len(vals) != 1 { |
| 316 | t.Fatalf("too many in header %s: %d", test.scheme, len(vals)) |
| 317 | } |
| 318 | if p := toSignatureParameter(keyIdParameter, test.pubKeyId); !strings.Contains(vals[0], p) { |
| 319 | t.Fatalf("%s\ndoes not contain\n%s", vals[0], p) |
| 320 | } else if p := toSignatureParameter(algorithmParameter, string(test.expectedSignatureAlgorithm)); !strings.Contains(vals[0], p) { |
| 321 | t.Fatalf("%s\ndoes not contain\n%s", vals[0], p) |
| 322 | } else if p := toHeaderSignatureParameters(headersParameter, test.headers); !strings.Contains(vals[0], p) { |
| 323 | t.Fatalf("%s\ndoes not contain\n%s", vals[0], p) |
| 324 | } else if !strings.Contains(vals[0], signatureParameter) { |
| 325 | t.Fatalf("%s\ndoes not contain\n%s", vals[0], signatureParameter) |
| 326 | } else if test.body != nil && req.Header.Get("Digest") != test.expectedDigest { |
| 327 | t.Fatalf("%s\ndoes not match\n%s", req.Header.Get("Digest"), test.expectedDigest) |
| 328 | } |
| 329 | // For schemes with an authScheme, enforce its is present and at the beginning |
| 330 | if len(test.scheme.authScheme()) > 0 { |
| 331 | if !strings.HasPrefix(vals[0], test.scheme.authScheme()) { |
| 332 | t.Fatalf("%s\ndoes not start with\n%s", vals[0], test.scheme.authScheme()) |
| 333 | } |
| 334 | } |
| 335 | } |
| 336 | for _, test := range tests { |
| 337 | t.Run(test.name, func(t *testing.T) { |
| 338 | testFn(t, test) |
| 339 | }) |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | func TestSignerResponse(t *testing.T) { |
| 344 | testFn := func(t *testing.T, test httpsigTest) { |
| 345 | s, _, err := NewSigner(test.prefs, test.digestAlg, test.headers, test.scheme, 0) |
| 346 | // Test response signing |
| 347 | resp := httptest.NewRecorder() |
| 348 | resp.HeaderMap.Set("Date", testDate) |
| 349 | if test.body == nil { |
| 350 | resp.HeaderMap.Set("Digest", testDigest) |
| 351 | } |
| 352 | err = s.SignResponse(test.privKey, test.pubKeyId, resp, test.body) |
| 353 | if test.expectErrorSigningResponse { |
| 354 | if err != nil { |
| 355 | // Skip rest of testing |
| 356 | return |
| 357 | } else { |
| 358 | t.Fatalf("expected error, got nil") |
| 359 | } |
| 360 | } |
| 361 | vals, ok := resp.HeaderMap[string(test.scheme)] |
| 362 | if !ok { |
| 363 | t.Fatalf("not in header %s", test.scheme) |
| 364 | } |
| 365 | if len(vals) != 1 { |
| 366 | t.Fatalf("too many in header %s: %d", test.scheme, len(vals)) |
| 367 | } |
| 368 | if p := toSignatureParameter(keyIdParameter, test.pubKeyId); !strings.Contains(vals[0], p) { |
| 369 | t.Fatalf("%s\ndoes not contain\n%s", vals[0], p) |
| 370 | } else if p := toSignatureParameter(algorithmParameter, string(test.expectedSignatureAlgorithm)); !strings.Contains(vals[0], p) { |
| 371 | t.Fatalf("%s\ndoes not contain\n%s", vals[0], p) |
| 372 | } else if p := toHeaderSignatureParameters(headersParameter, test.headers); !strings.Contains(vals[0], p) { |
| 373 | t.Fatalf("%s\ndoes not contain\n%s", vals[0], p) |
| 374 | } else if !strings.Contains(vals[0], signatureParameter) { |
| 375 | t.Fatalf("%s\ndoes not contain\n%s", vals[0], signatureParameter) |
| 376 | } else if test.body != nil && resp.Header().Get("Digest") != test.expectedDigest { |
| 377 | t.Fatalf("%s\ndoes not match\n%s", resp.Header().Get("Digest"), test.expectedDigest) |
| 378 | } |
| 379 | // For schemes with an authScheme, enforce its is present and at the beginning |
| 380 | if len(test.scheme.authScheme()) > 0 { |
| 381 | if !strings.HasPrefix(vals[0], test.scheme.authScheme()) { |
| 382 | t.Fatalf("%s\ndoes not start with\n%s", vals[0], test.scheme.authScheme()) |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | for _, test := range tests { |
| 387 | t.Run(test.name, func(t *testing.T) { |
| 388 | testFn(t, test) |
| 389 | }) |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | func TestNewSignerRequestMissingHeaders(t *testing.T) { |
| 394 | failingTests := []struct { |
| 395 | name string |
| 396 | prefs []Algorithm |
| 397 | digestAlg DigestAlgorithm |
| 398 | headers []string |
| 399 | scheme SignatureScheme |
| 400 | privKey crypto.PrivateKey |
| 401 | pubKeyId string |
| 402 | expectedAlgorithm Algorithm |
| 403 | expectedSignatureAlgorithm string |
| 404 | }{ |
| 405 | { |
| 406 | name: "wants digest", |
| 407 | prefs: []Algorithm{RSA_SHA512}, |
| 408 | digestAlg: DigestSha256, |
| 409 | headers: []string{"Date", "Digest"}, |
| 410 | scheme: Signature, |
| 411 | privKey: privKey, |
| 412 | pubKeyId: "pubKeyId", |
| 413 | expectedSignatureAlgorithm: "hs2019", |
| 414 | expectedAlgorithm: RSA_SHA512, |
| 415 | }, |
| 416 | } |
| 417 | for _, test := range failingTests { |
| 418 | t.Run(test.name, func(t *testing.T) { |
| 419 | test := test |
| 420 | s, a, err := NewSigner(test.prefs, test.digestAlg, test.headers, test.scheme, 0) |
| 421 | if err != nil { |
| 422 | t.Fatalf("%s", err) |
| 423 | } |
| 424 | if a != test.expectedAlgorithm { |
| 425 | t.Fatalf("got %s, want %s", a, test.expectedAlgorithm) |
| 426 | } |
| 427 | req, err := http.NewRequest(testMethod, testUrl, nil) |
| 428 | if err != nil { |
| 429 | t.Fatalf("%s", err) |
| 430 | } |
| 431 | req.Header.Set("Date", testDate) |
| 432 | err = s.SignRequest(test.privKey, test.pubKeyId, req, nil) |
| 433 | if err == nil { |
| 434 | t.Fatalf("expect error but got nil") |
| 435 | } |
| 436 | }) |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | func TestNewSignerResponseMissingHeaders(t *testing.T) { |
| 441 | failingTests := []struct { |
| 442 | name string |
| 443 | prefs []Algorithm |
| 444 | digestAlg DigestAlgorithm |
| 445 | headers []string |
| 446 | scheme SignatureScheme |
| 447 | privKey crypto.PrivateKey |
| 448 | pubKeyId string |
| 449 | expectedAlgorithm Algorithm |
| 450 | expectErrorSigningResponse bool |
| 451 | expectedSignatureAlgorithm string |
| 452 | }{ |
| 453 | { |
| 454 | name: "want digest", |
| 455 | prefs: []Algorithm{RSA_SHA512}, |
| 456 | digestAlg: DigestSha256, |
| 457 | headers: []string{"Date", "Digest"}, |
| 458 | scheme: Signature, |
| 459 | privKey: privKey, |
| 460 | pubKeyId: "pubKeyId", |
| 461 | expectedSignatureAlgorithm: "hs2019", |
| 462 | expectedAlgorithm: RSA_SHA512, |
| 463 | }, |
| 464 | } |
| 465 | for _, test := range failingTests { |
| 466 | t.Run(test.name, func(t *testing.T) { |
| 467 | test := test |
| 468 | s, a, err := NewSigner(test.prefs, test.digestAlg, test.headers, test.scheme, 0) |
| 469 | if err != nil { |
| 470 | t.Fatalf("%s", err) |
| 471 | } |
| 472 | if a != test.expectedAlgorithm { |
| 473 | t.Fatalf("got %s, want %s", a, test.expectedAlgorithm) |
| 474 | } |
| 475 | resp := httptest.NewRecorder() |
| 476 | resp.HeaderMap.Set("Date", testDate) |
| 477 | resp.HeaderMap.Set("Digest", testDigest) |
| 478 | err = s.SignResponse(test.privKey, test.pubKeyId, resp, nil) |
| 479 | if err != nil { |
| 480 | t.Fatalf("expected error, got nil") |
| 481 | } |
| 482 | }) |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | func TestNewVerifier(t *testing.T) { |
| 487 | for _, test := range tests { |
| 488 | t.Run(test.name, func(t *testing.T) { |
| 489 | test := test |
| 490 | // Prepare |
| 491 | req, err := http.NewRequest(testMethod, testUrl, nil) |
| 492 | if err != nil { |
| 493 | t.Fatalf("%s", err) |
| 494 | } |
| 495 | req.Header.Set("Date", testDate) |
| 496 | if test.body == nil { |
| 497 | req.Header.Set("Digest", testDigest) |
| 498 | } |
| 499 | s, _, err := NewSigner(test.prefs, test.digestAlg, test.headers, test.scheme, 0) |
| 500 | if err != nil { |
| 501 | t.Fatalf("%s", err) |
| 502 | } |
| 503 | err = s.SignRequest(test.privKey, test.pubKeyId, req, test.body) |
| 504 | if err != nil { |
| 505 | t.Fatalf("%s", err) |
| 506 | } |
| 507 | // Test verification |
| 508 | v, err := NewVerifier(req) |
| 509 | if err != nil { |
| 510 | t.Fatalf("%s", err) |
| 511 | } |
| 512 | if v.KeyId() != test.pubKeyId { |
| 513 | t.Fatalf("got %s, want %s", v.KeyId(), test.pubKeyId) |
| 514 | } |
| 515 | err = v.Verify(test.pubKey, test.expectedAlgorithm) |
| 516 | if err != nil { |
| 517 | t.Fatalf("%s", err) |
| 518 | } |
| 519 | }) |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | func TestNewResponseVerifier(t *testing.T) { |
| 524 | for _, test := range tests { |
| 525 | t.Run(test.name, func(t *testing.T) { |
| 526 | test := test |
| 527 | if test.expectErrorSigningResponse { |
| 528 | return |
| 529 | } |
| 530 | // Prepare |
| 531 | resp := httptest.NewRecorder() |
| 532 | resp.HeaderMap.Set("Date", testDate) |
| 533 | if test.body == nil { |
| 534 | resp.HeaderMap.Set("Digest", testDigest) |
| 535 | } |
| 536 | s, _, err := NewSigner(test.prefs, test.digestAlg, test.headers, test.scheme, 0) |
| 537 | if err != nil { |
| 538 | t.Fatalf("%s", err) |
| 539 | } |
| 540 | err = s.SignResponse(test.privKey, test.pubKeyId, resp, test.body) |
| 541 | if err != nil { |
| 542 | t.Fatalf("%s", err) |
| 543 | } |
| 544 | // Test verification |
| 545 | v, err := NewResponseVerifier(resp.Result()) |
| 546 | if err != nil { |
| 547 | t.Fatalf("%s", err) |
| 548 | } |
| 549 | if v.KeyId() != test.pubKeyId { |
| 550 | t.Fatalf("got %s, want %s", v.KeyId(), test.pubKeyId) |
| 551 | } |
| 552 | err = v.Verify(test.pubKey, test.expectedAlgorithm) |
| 553 | if err != nil { |
| 554 | t.Fatalf("%s", err) |
| 555 | } |
| 556 | }) |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | // Test_Signing_HTTP_Messages_AppendixC implement tests from Appendix C |
| 561 | // in the http signatures specification: |
| 562 | // https://tools.ietf.org/html/draft-cavage-http-signatures-10#appendix-C |
| 563 | func Test_Signing_HTTP_Messages_AppendixC(t *testing.T) { |
| 564 | specTests := []struct { |
| 565 | name string |
| 566 | headers []string |
| 567 | expectedSignature string |
| 568 | }{ |
| 569 | { |
| 570 | name: "C.1. Default Test", |
| 571 | headers: []string{}, |
| 572 | // NOTE: In the Appendix C tests, the following is NOT included: |
| 573 | // `headers="date"` |
| 574 | // But httpsig will ALWAYS explicitly list the headers used in its |
| 575 | // signature. Hence, I have introduced it here. |
| 576 | // |
| 577 | // NOTE: In verification, if there are no headers listed, the |
| 578 | // default headers (date) are indeed used as required by the |
| 579 | // specification. |
| 580 | expectedSignature: `Authorization: Signature keyId="Test",algorithm="hs2019",headers="date",signature="SjWJWbWN7i0wzBvtPl8rbASWz5xQW6mcJmn+ibttBqtifLN7Sazz6m79cNfwwb8DMJ5cou1s7uEGKKCs+FLEEaDV5lp7q25WqS+lavg7T8hc0GppauB6hbgEKTwblDHYGEtbGmtdHgVCk9SuS13F0hZ8FD0k/5OxEPXe5WozsbM="`, |
| 581 | }, |
| 582 | { |
| 583 | name: "C.2. Basic Test", |
| 584 | headers: []string{"(request-target)", "host", "date"}, |
| 585 | expectedSignature: `Authorization: Signature keyId="Test",algorithm="hs2019",headers="(request-target) host date",signature="qdx+H7PHHDZgy4y/Ahn9Tny9V3GP6YgBPyUXMmoxWtLbHpUnXS2mg2+SbrQDMCJypxBLSPQR2aAjn7ndmw2iicw3HMbe8VfEdKFYRqzic+efkb3nndiv/x1xSHDJWeSWkx3ButlYSuBskLu6kd9Fswtemr3lgdDEmn04swr2Os0="`, |
| 586 | }, |
| 587 | { |
| 588 | name: "C.3. All Headers Test", |
| 589 | headers: []string{"(request-target)", "host", "date", "content-type", "digest", "content-length"}, |
| 590 | expectedSignature: `Authorization: Signature keyId="Test",algorithm="hs2019",headers="(request-target) host date content-type digest content-length",signature="vSdrb+dS3EceC9bcwHSo4MlyKS59iFIrhgYkz8+oVLEEzmYZZvRs8rgOp+63LEM3v+MFHB32NfpB2bEKBIvB1q52LaEUHFv120V01IL+TAD48XaERZFukWgHoBTLMhYS2Gb51gWxpeIq8knRmPnYePbF5MOkR0Zkly4zKH7s1dE="`, |
| 591 | }, |
| 592 | } |
| 593 | |
| 594 | for _, test := range specTests { |
| 595 | t.Run(test.name, func(t *testing.T) { |
| 596 | test := test |
| 597 | r, err := http.NewRequest("POST", "http://example.com/foo?param=value&pet=dog", bytes.NewBuffer([]byte(testSpecBody))) |
| 598 | if err != nil { |
| 599 | t.Fatalf("error creating request: %s", err) |
| 600 | } |
| 601 | |
| 602 | r.Header["Date"] = []string{testSpecDate} |
| 603 | r.Header["Host"] = []string{r.URL.Host} |
| 604 | r.Header["Content-Length"] = []string{strconv.Itoa(len(testSpecBody))} |
| 605 | r.Header["Content-Type"] = []string{"application/json"} |
| 606 | setDigest(r) |
| 607 | |
| 608 | s, _, err := NewSigner([]Algorithm{RSA_SHA256}, DigestSha256, test.headers, Authorization, 0) |
| 609 | if err != nil { |
| 610 | t.Fatalf("error creating signer: %s", err) |
| 611 | } |
| 612 | |
| 613 | if err := s.SignRequest(testSpecRSAPrivateKey, "Test", r, nil); err != nil { |
| 614 | t.Fatalf("error signing request: %s", err) |
| 615 | } |
| 616 | |
| 617 | expectedAuth := test.expectedSignature |
| 618 | gotAuth := fmt.Sprintf("Authorization: %s", r.Header["Authorization"][0]) |
| 619 | if gotAuth != expectedAuth { |
| 620 | t.Errorf("Signature string mismatch\nGot: %s\nWant: %s", gotAuth, expectedAuth) |
| 621 | } |
| 622 | }) |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | func TestSigningEd25519(t *testing.T) { |
| 627 | specTests := []struct { |
| 628 | name string |
| 629 | headers []string |
| 630 | expectedSignature string |
| 631 | }{ |
| 632 | { |
| 633 | name: "Default Test", |
| 634 | headers: []string{}, |
| 635 | // NOTE: In the Appendix C tests, the following is NOT included: |
| 636 | // `headers="date"` |
| 637 | // But httpsig will ALWAYS explicitly list the headers used in its |
| 638 | // signature. Hence, I have introduced it here. |
| 639 | // |
| 640 | // NOTE: In verification, if there are no headers listed, the |
| 641 | // default headers (date) are indeed used as required by the |
| 642 | // specification. |
| 643 | expectedSignature: `Authorization: Signature keyId="Test",algorithm="hs2019",headers="date",signature="6G9bNnUfph4pnl3j8l4UTcSPJVg6r4tM73eWFAn+w4IdIi8yzzZs65QlgM31lAuVCRKlqMzME9VGgMt16nU1AQ=="`, |
| 644 | }, |
| 645 | { |
| 646 | name: "Basic Test", |
| 647 | headers: []string{"(request-target)", "host", "date"}, |
| 648 | expectedSignature: `Authorization: Signature keyId="Test",algorithm="hs2019",headers="(request-target) host date",signature="upsoNpw5oJTD3lTIQHEnDGWTaKmlT7o2c9Lz3kqy2UTwOEpEop3Sd7F/K2bYD2lQ4AH1HRyvC4/9AcKgNBg1AA=="`, |
| 649 | }, |
| 650 | { |
| 651 | name: "All Headers Test", |
| 652 | headers: []string{"(request-target)", "host", "date", "content-type", "digest", "content-length"}, |
| 653 | expectedSignature: `Authorization: Signature keyId="Test",algorithm="hs2019",headers="(request-target) host date content-type digest content-length",signature="UkxhZl0W5/xcuCIP5xOPv4V6rX0TmaV2lmrYYGWauKhdFHihpW80tCqTNFDhyD+nYeGNCRSFRHmDS0bGm0PVAg=="`, |
| 654 | }, |
| 655 | } |
| 656 | |
| 657 | for _, test := range specTests { |
| 658 | t.Run(test.name, func(t *testing.T) { |
| 659 | test := test |
| 660 | r, err := http.NewRequest("POST", "http://example.com/foo?param=value&pet=dog", bytes.NewBuffer([]byte(testSpecBody))) |
| 661 | if err != nil { |
| 662 | t.Fatalf("error creating request: %s", err) |
| 663 | } |
| 664 | |
| 665 | r.Header["Date"] = []string{testSpecDate} |
| 666 | r.Header["Host"] = []string{r.URL.Host} |
| 667 | r.Header["Content-Length"] = []string{strconv.Itoa(len(testSpecBody))} |
| 668 | r.Header["Content-Type"] = []string{"application/json"} |
| 669 | setDigest(r) |
| 670 | |
| 671 | s, _, err := NewSigner([]Algorithm{ED25519}, DigestSha256, test.headers, Authorization, 0) |
| 672 | if err != nil { |
| 673 | t.Fatalf("error creating signer: %s", err) |
| 674 | } |
| 675 | |
| 676 | if err := s.SignRequest(testEd25519PrivateKey, "Test", r, nil); err != nil { |
| 677 | t.Fatalf("error signing request: %s", err) |
| 678 | } |
| 679 | |
| 680 | expectedAuth := test.expectedSignature |
| 681 | gotAuth := fmt.Sprintf("Authorization: %s", r.Header["Authorization"][0]) |
| 682 | if gotAuth != expectedAuth { |
| 683 | t.Errorf("Signature string mismatch\nGot: %s\nWant: %s", gotAuth, expectedAuth) |
| 684 | } |
| 685 | }) |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | // Test_Verifying_HTTP_Messages_AppendixC implement tests from Appendix C |
| 690 | // in the http signatures specification: |
| 691 | // https://tools.ietf.org/html/draft-cavage-http-signatures-10#appendix-C |
| 692 | func Test_Verifying_HTTP_Messages_AppendixC(t *testing.T) { |
| 693 | specTests := []struct { |
| 694 | name string |
| 695 | headers []string |
| 696 | signature string |
| 697 | }{ |
| 698 | { |
| 699 | name: "C.1. Default Test", |
| 700 | headers: []string{}, |
| 701 | signature: `Signature keyId="Test",algorithm="rsa-sha256",signature="SjWJWbWN7i0wzBvtPl8rbASWz5xQW6mcJmn+ibttBqtifLN7Sazz6m79cNfwwb8DMJ5cou1s7uEGKKCs+FLEEaDV5lp7q25WqS+lavg7T8hc0GppauB6hbgEKTwblDHYGEtbGmtdHgVCk9SuS13F0hZ8FD0k/5OxEPXe5WozsbM="`, |
| 702 | }, |
| 703 | { |
| 704 | name: "C.2. Basic Test", |
| 705 | headers: []string{"(request-target)", "host", "date"}, |
| 706 | signature: `Signature keyId="Test",algorithm="rsa-sha256",headers="(request-target) host date",signature="qdx+H7PHHDZgy4y/Ahn9Tny9V3GP6YgBPyUXMmoxWtLbHpUnXS2mg2+SbrQDMCJypxBLSPQR2aAjn7ndmw2iicw3HMbe8VfEdKFYRqzic+efkb3nndiv/x1xSHDJWeSWkx3ButlYSuBskLu6kd9Fswtemr3lgdDEmn04swr2Os0="`, |
| 707 | }, |
| 708 | { |
| 709 | name: "C.3. All Headers Test", |
| 710 | headers: []string{"(request-target)", "host", "date", "content-type", "digest", "content-length"}, |
| 711 | signature: `Signature keyId="Test",algorithm="rsa-sha256",headers="(request-target) host date content-type digest content-length",signature="vSdrb+dS3EceC9bcwHSo4MlyKS59iFIrhgYkz8+oVLEEzmYZZvRs8rgOp+63LEM3v+MFHB32NfpB2bEKBIvB1q52LaEUHFv120V01IL+TAD48XaERZFukWgHoBTLMhYS2Gb51gWxpeIq8knRmPnYePbF5MOkR0Zkly4zKH7s1dE="`, |
| 712 | }, |
| 713 | } |
| 714 | |
| 715 | for _, test := range specTests { |
| 716 | t.Run(test.name, func(t *testing.T) { |
| 717 | test := test |
| 718 | r, err := http.NewRequest("POST", "http://example.com/foo?param=value&pet=dog", bytes.NewBuffer([]byte(testSpecBody))) |
| 719 | if err != nil { |
| 720 | t.Fatalf("error creating request: %s", err) |
| 721 | } |
| 722 | |
| 723 | r.Header["Date"] = []string{testSpecDate} |
| 724 | r.Header["Host"] = []string{r.URL.Host} |
| 725 | r.Header["Content-Length"] = []string{strconv.Itoa(len(testSpecBody))} |
| 726 | r.Header["Content-Type"] = []string{"application/json"} |
| 727 | setDigest(r) |
| 728 | r.Header["Authorization"] = []string{test.signature} |
| 729 | |
| 730 | v, err := NewVerifier(r) |
| 731 | if err != nil { |
| 732 | t.Fatalf("error creating verifier: %s", err) |
| 733 | } |
| 734 | |
| 735 | if "Test" != v.KeyId() { |
| 736 | t.Errorf("KeyId mismatch\nGot: %s\nWant: Test", v.KeyId()) |
| 737 | } |
| 738 | if err := v.Verify(testSpecRSAPublicKey, RSA_SHA256); err != nil { |
| 739 | t.Errorf("Verification failure: %s", err) |
| 740 | } |
| 741 | }) |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | func TestVerifyingEd25519(t *testing.T) { |
| 746 | specTests := []struct { |
| 747 | name string |
| 748 | headers []string |
| 749 | signature string |
| 750 | }{ |
| 751 | { |
| 752 | name: "Default Test", |
| 753 | headers: []string{}, |
| 754 | signature: `Signature keyId="Test",algorithm="hs2019",headers="date",signature="6G9bNnUfph4pnl3j8l4UTcSPJVg6r4tM73eWFAn+w4IdIi8yzzZs65QlgM31lAuVCRKlqMzME9VGgMt16nU1AQ=="`, |
| 755 | }, |
| 756 | { |
| 757 | name: "Basic Test", |
| 758 | headers: []string{"(request-target)", "host", "date"}, |
| 759 | signature: `Signature keyId="Test",algorithm="hs2019",headers="(request-target) host date",signature="upsoNpw5oJTD3lTIQHEnDGWTaKmlT7o2c9Lz3kqy2UTwOEpEop3Sd7F/K2bYD2lQ4AH1HRyvC4/9AcKgNBg1AA=="`, |
| 760 | }, |
| 761 | { |
| 762 | name: "All Headers Test", |
| 763 | headers: []string{"(request-target)", "host", "date", "content-type", "digest", "content-length"}, |
| 764 | signature: `Signature keyId="Test",algorithm="hs2019",headers="(request-target) host date content-type digest content-length",signature="UkxhZl0W5/xcuCIP5xOPv4V6rX0TmaV2lmrYYGWauKhdFHihpW80tCqTNFDhyD+nYeGNCRSFRHmDS0bGm0PVAg=="`, |
| 765 | }, |
| 766 | } |
| 767 | |
| 768 | for _, test := range specTests { |
| 769 | t.Run(test.name, func(t *testing.T) { |
| 770 | test := test |
| 771 | r, err := http.NewRequest("POST", "http://example.com/foo?param=value&pet=dog", bytes.NewBuffer([]byte(testSpecBody))) |
| 772 | if err != nil { |
| 773 | t.Fatalf("error creating request: %s", err) |
| 774 | } |
| 775 | |
| 776 | r.Header["Date"] = []string{testSpecDate} |
| 777 | r.Header["Host"] = []string{r.URL.Host} |
| 778 | r.Header["Content-Length"] = []string{strconv.Itoa(len(testSpecBody))} |
| 779 | r.Header["Content-Type"] = []string{"application/json"} |
| 780 | setDigest(r) |
| 781 | r.Header["Authorization"] = []string{test.signature} |
| 782 | |
| 783 | v, err := NewVerifier(r) |
| 784 | if err != nil { |
| 785 | t.Fatalf("error creating verifier: %s", err) |
| 786 | } |
| 787 | |
| 788 | if "Test" != v.KeyId() { |
| 789 | t.Errorf("KeyId mismatch\nGot: %s\nWant: Test", v.KeyId()) |
| 790 | } |
| 791 | if err := v.Verify(testEd25519PublicKey, ED25519); err != nil { |
| 792 | t.Errorf("Verification failure: %s", err) |
| 793 | } |
| 794 | }) |
| 795 | } |
| 796 | } |
| 797 | |
| 798 | func loadPrivateKey(keyData []byte) (*rsa.PrivateKey, error) { |
| 799 | pem, _ := pem.Decode(keyData) |
| 800 | if pem.Type != "RSA PRIVATE KEY" { |
| 801 | return nil, fmt.Errorf("RSA private key is of the wrong type: %s", pem.Type) |
| 802 | } |
| 803 | |
| 804 | return x509.ParsePKCS1PrivateKey(pem.Bytes) |
| 805 | } |
| 806 | |
| 807 | // taken from https://blainsmith.com/articles/signing-jwts-with-gos-crypto-ed25519/ |
| 808 | func loadEd25519PrivateKey(keyData []byte) (ed25519.PrivateKey, error) { |
| 809 | var block *pem.Block |
| 810 | block, _ = pem.Decode(keyData) |
| 811 | |
| 812 | var asn1PrivKey ed25519PrivKey |
| 813 | asn1.Unmarshal(block.Bytes, &asn1PrivKey) |
| 814 | |
| 815 | // [2:] is skipping the byte for TAG and the byte for LEN |
| 816 | // see also https://tools.ietf.org/html/draft-ietf-curdle-pkix-10#section-10.3 |
| 817 | return ed25519.NewKeyFromSeed(asn1PrivKey.PrivateKey[2:]), nil |
| 818 | } |
| 819 | |
| 820 | func loadPublicKey(keyData []byte) (*rsa.PublicKey, error) { |
| 821 | pem, _ := pem.Decode(keyData) |
| 822 | if pem.Type != "PUBLIC KEY" { |
| 823 | return nil, fmt.Errorf("public key is of the wrong type: %s", pem.Type) |
| 824 | } |
| 825 | |
| 826 | key, err := x509.ParsePKIXPublicKey(pem.Bytes) |
| 827 | if err != nil { |
| 828 | return nil, err |
| 829 | } |
| 830 | |
| 831 | return key.(*rsa.PublicKey), nil |
| 832 | } |
| 833 | |
| 834 | // taken from https://blainsmith.com/articles/signing-jwts-with-gos-crypto-ed25519/ |
| 835 | func loadEd25519PublicKey(keyData []byte) (ed25519.PublicKey, error) { |
| 836 | var block *pem.Block |
| 837 | block, _ = pem.Decode(keyData) |
| 838 | |
| 839 | var asn1PubKey ed25519PubKey |
| 840 | asn1.Unmarshal(block.Bytes, &asn1PubKey) |
| 841 | |
| 842 | return ed25519.PublicKey(asn1PubKey.PublicKey.Bytes), nil |
| 843 | } |
| 844 | |
| 845 | func setDigest(r *http.Request) ([]byte, error) { |
| 846 | var bodyBytes []byte |
| 847 | if _, ok := r.Header["Digest"]; !ok { |
| 848 | body := "" |
| 849 | if r.Body != nil { |
| 850 | var err error |
| 851 | bodyBytes, err = ioutil.ReadAll(r.Body) |
| 852 | if err != nil { |
| 853 | return nil, fmt.Errorf("error reading body. %v", err) |
| 854 | } |
| 855 | |
| 856 | // And now set a new body, which will simulate the same data we read: |
| 857 | r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) |
| 858 | body = string(bodyBytes) |
| 859 | } |
| 860 | |
| 861 | d := sha256.Sum256([]byte(body)) |
| 862 | r.Header["Digest"] = []string{fmt.Sprintf("SHA-256=%s", base64.StdEncoding.EncodeToString(d[:]))} |
| 863 | } |
| 864 | |
| 865 | return bodyBytes, nil |
| 866 | } |
| 867 | |
| 868 | const testSpecBody = `{"hello": "world"}` |
| 869 | |
| 870 | const testSpecDate = `Sun, 05 Jan 2014 21:31:40 GMT` |
| 871 | |
| 872 | const testSpecPrivateKeyPEM = `-----BEGIN RSA PRIVATE KEY----- |
| 873 | MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF |
| 874 | NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F |
| 875 | UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB |
| 876 | AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA |
| 877 | QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK |
| 878 | kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg |
| 879 | f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u |
| 880 | 412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc |
| 881 | mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 |
| 882 | kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA |
| 883 | gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW |
| 884 | G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI |
| 885 | 7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== |
| 886 | -----END RSA PRIVATE KEY-----` |
| 887 | |
| 888 | const testSpecPublicKeyPEM = `-----BEGIN PUBLIC KEY----- |
| 889 | MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCFENGw33yGihy92pDjZQhl0C3 |
| 890 | 6rPJj+CvfSC8+q28hxA161QFNUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6 |
| 891 | Z4UMR7EOcpfdUE9Hf3m/hs+FUR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJw |
| 892 | oYi+1hqp1fIekaxsyQIDAQAB |
| 893 | -----END PUBLIC KEY-----` |
| 894 | |
| 895 | const testEd25519PrivateKeyPEM = `-----BEGIN PRIVATE KEY----- |
| 896 | MC4CAQAwBQYDK2VwBCIEIAP+PK4NtdzCe04sbtwBvf9IShlky298SMMBqkCCToHn |
| 897 | -----END PRIVATE KEY-----` |
| 898 | |
| 899 | const testEd25519PublicKeyPEM = `-----BEGIN PUBLIC KEY----- |
| 900 | MCowBQYDK2VwAyEAhyP+7zpNCsr7/ipGJjK0zVszTEQ5tooyX3VLAnBSc1c= |
| 901 | -----END PUBLIC KEY-----` |