(ctx context.Context, db database.Store, sessionTokenFunc func(r *http.Request) string, r *http.Request)
| 502 | } |
| 503 | |
| 504 | func apiKeyFromRequestValidate(ctx context.Context, db database.Store, sessionTokenFunc func(r *http.Request) string, r *http.Request) (*database.APIKey, *ValidateAPIKeyError) { |
| 505 | tokenFunc := APITokenFromRequest |
| 506 | if sessionTokenFunc != nil { |
| 507 | tokenFunc = sessionTokenFunc |
| 508 | } |
| 509 | |
| 510 | token := tokenFunc(r) |
| 511 | if token == "" { |
| 512 | return nil, &ValidateAPIKeyError{ |
| 513 | Code: http.StatusUnauthorized, |
| 514 | Response: codersdk.Response{ |
| 515 | Message: SignedOutErrorMessage, |
| 516 | Detail: fmt.Sprintf("Cookie %q or query parameter must be provided.", codersdk.SessionTokenCookie), |
| 517 | }, |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | keyID, keySecret, err := SplitAPIToken(token) |
| 522 | if err != nil { |
| 523 | return nil, &ValidateAPIKeyError{ |
| 524 | Code: http.StatusUnauthorized, |
| 525 | Response: codersdk.Response{ |
| 526 | Message: SignedOutErrorMessage, |
| 527 | Detail: "Invalid API key format: " + err.Error(), |
| 528 | }, |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | //nolint:gocritic // System needs to fetch API key to check if it's valid. |
| 533 | key, err := db.GetAPIKeyByID(dbauthz.AsSystemRestricted(ctx), keyID) |
| 534 | if err != nil { |
| 535 | if errors.Is(err, sql.ErrNoRows) { |
| 536 | return nil, &ValidateAPIKeyError{ |
| 537 | Code: http.StatusUnauthorized, |
| 538 | Response: codersdk.Response{ |
| 539 | Message: SignedOutErrorMessage, |
| 540 | Detail: "API key is invalid.", |
| 541 | }, |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | return nil, &ValidateAPIKeyError{ |
| 546 | Code: http.StatusInternalServerError, |
| 547 | Response: codersdk.Response{ |
| 548 | Message: internalErrorMessage, |
| 549 | Detail: fmt.Sprintf("Internal error fetching API key by id. %s", err.Error()), |
| 550 | }, |
| 551 | Hard: true, |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | // Checking to see if the secret is valid. |
| 556 | if !apikey.ValidateHash(key.HashedSecret, keySecret) { |
| 557 | return nil, &ValidateAPIKeyError{ |
| 558 | Code: http.StatusUnauthorized, |
| 559 | Response: codersdk.Response{ |
| 560 | Message: SignedOutErrorMessage, |
| 561 | Detail: "API key secret is invalid.", |
no test coverage detected