|
| 1 | +import { EndpointSpec } from "core/endpoint/types"; |
| 2 | +import { FetchConfig } from "core/request/types"; |
| 3 | +import { expect, test } from "vitest"; |
| 4 | +import { checkRequiredScopes, applyCredentials } from "./credentials"; |
| 5 | +import { AuthCredentials, IntegrationAuthentication } from "./types"; |
| 6 | + |
| 7 | +test("Required scopes present", async () => { |
| 8 | + const credentials: AuthCredentials = { |
| 9 | + type: "oauth2", |
| 10 | + name: "authName", |
| 11 | + accessToken: "token", |
| 12 | + scopes: ["scope1", "scope2"], |
| 13 | + }; |
| 14 | + |
| 15 | + const requiredScopes = ["scope1", "scope2"]; |
| 16 | + |
| 17 | + const result = checkRequiredScopes(requiredScopes, credentials); |
| 18 | + expect(result.success).toEqual(true); |
| 19 | +}); |
| 20 | + |
| 21 | +test("Required scopes missing", async () => { |
| 22 | + const credentials: AuthCredentials = { |
| 23 | + type: "oauth2", |
| 24 | + name: "authName", |
| 25 | + accessToken: "token", |
| 26 | + scopes: ["scope1", "scope2"], |
| 27 | + }; |
| 28 | + |
| 29 | + const requiredScopes = ["scope1", "scope2", "scope3"]; |
| 30 | + |
| 31 | + const result = checkRequiredScopes(requiredScopes, credentials); |
| 32 | + expect(result.success).toEqual(false); |
| 33 | + if (result.success) throw new Error("Should not be success"); |
| 34 | + expect(result.missingScopes).toEqual(["scope3"]); |
| 35 | +}); |
| 36 | + |
| 37 | +test("Applied credentials", async () => { |
| 38 | + const credentials: AuthCredentials = { |
| 39 | + type: "oauth2", |
| 40 | + name: "authName", |
| 41 | + accessToken: "123456", |
| 42 | + scopes: ["scope1", "scope2"], |
| 43 | + }; |
| 44 | + const endpointSecurity: EndpointSpec["security"] = { |
| 45 | + authName: ["scope1", "scope2"], |
| 46 | + }; |
| 47 | + |
| 48 | + const integrationAuthentication: IntegrationAuthentication = { |
| 49 | + authName: { |
| 50 | + type: "oauth2", |
| 51 | + placement: { |
| 52 | + in: "header", |
| 53 | + type: "bearer", |
| 54 | + key: "Authorization", |
| 55 | + }, |
| 56 | + authorizationUrl: "https://example.com", |
| 57 | + tokenUrl: "https://example.com", |
| 58 | + flow: "accessCode", |
| 59 | + scopes: { |
| 60 | + scope1: "scope1", |
| 61 | + scope2: "scope2", |
| 62 | + }, |
| 63 | + }, |
| 64 | + }; |
| 65 | + |
| 66 | + const existingFetch: FetchConfig = { |
| 67 | + url: "https://example.com", |
| 68 | + method: "GET", |
| 69 | + headers: { |
| 70 | + "Content-Type": "application/json", |
| 71 | + }, |
| 72 | + }; |
| 73 | + |
| 74 | + const fetchConfig = applyCredentials(existingFetch, { |
| 75 | + endpointSecurity, |
| 76 | + authentication: integrationAuthentication, |
| 77 | + credentials, |
| 78 | + }); |
| 79 | + |
| 80 | + expect(fetchConfig.headers.Authorization).toEqual("Bearer 123456"); |
| 81 | + expect(fetchConfig.headers["Content-Type"]).toEqual("application/json"); |
| 82 | +}); |
0 commit comments