This commit is contained in:
Steve Faulkner 2019-06-11 16:19:24 -04:00 коммит произвёл GitHub
Родитель 51fc20c23d
Коммит 2292b3cc42
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
27 изменённых файлов: 76 добавлений и 91 удалений

Просмотреть файл

@ -12,7 +12,7 @@ const CosmosClient = cosmos.CosmosClient;
const endpoint = "[hostendpoint]"; // Add your endpoint
const masterKey = "[database account masterkey]"; // Add the masterkey of the endpoint
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
const databaseDefinition = { id: "sample database" };
const collectionDefinition = { id: "sample collection" };

Просмотреть файл

@ -11,7 +11,7 @@ const endpoint = config.connection.endpoint;
const masterKey = config.connection.authKey;
// Establish a new instance of the CosmosClient to be used throughout this demo
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
// We'll use the same pk value for all these samples
const pk = "0";

Просмотреть файл

@ -18,7 +18,7 @@ const endpoint = config.connection.endpoint;
const masterKey = config.connection.authKey;
// Establish a new instance of the CosmosClient to be used throughout this demo
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
//---------------------------------------------------------------------------------
// This demo performs a few steps

Просмотреть файл

@ -18,7 +18,7 @@ const endpoint = config.connection.endpoint;
const masterKey = config.connection.authKey;
// Establish a new instance of the CosmosClient to be used throughout this demo
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
//---------------------------------------------------------------------------------------------------
// This demo performs the following CRUD operations on a Database

Просмотреть файл

@ -19,7 +19,7 @@ const endpoint = config.connection.endpoint;
const masterKey = config.connection.authKey;
// Establish a new instance of the CosmosClient to be used throughout this demo
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
//IMPORTANT:
//this sample creates and delete containers at least 7 times.

Просмотреть файл

@ -24,7 +24,7 @@ const getItemDefinitions = function() {
};
// Establish a new instance of the CosmosClient to be used throughout this demo
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
//-------------------------------------------------------------------------------------------------------
// This demo performs a few steps

Просмотреть файл

@ -21,7 +21,7 @@ const endpoint = config.connection.endpoint;
const masterKey = config.connection.authKey;
// Establish a new instance of the DocumentDBClient to be used throughout this demo
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
// Path to stored procedure definition
const sprocDefinition = require("./JS/upsert");

Просмотреть файл

@ -25,7 +25,7 @@ const item2Name = "item2";
const item3Name = "item3";
// Establish a new instance of the DocumentDBClient to be used throughout this demo
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
async function run() {
const resources = await init();

Просмотреть файл

@ -558,7 +558,7 @@ export class ClientContext {
private buildHeaders(requestContext: RequestContext) {
return getHeaders({
authOptions: this.cosmosClientOptions.auth,
clientOptions: this.cosmosClientOptions,
defaultHeaders: { ...this.cosmosClientOptions.defaultHeaders, ...requestContext.options.initialHeaders },
verb: requestContext.method,
path: requestContext.path,

Просмотреть файл

@ -52,11 +52,6 @@ export class CosmosClient {
private clientContext: ClientContext;
constructor(private options: CosmosClientOptions) {
options.auth = options.auth || {};
if (options.key) {
options.auth.key = options.key;
}
options.connectionPolicy = Object.assign({}, defaultConnectionPolicy, options.connectionPolicy);
options.defaultHeaders = options.defaultHeaders || {};

Просмотреть файл

@ -1,4 +1,5 @@
import { AuthOptions } from "./auth";
import { TokenProvider } from "./auth";
import { PermissionDefinition } from "./client";
import { ConnectionPolicy, ConsistencyLevel } from "./documents";
import { PluginConfig } from "./plugins/Plugin";
import { CosmosHeaders } from "./queryExecutionContext/CosmosHeaders";
@ -15,10 +16,18 @@ export interface Agent {
export interface CosmosClientOptions {
/** The service endpoint to use to create the client. */
endpoint: string;
/** The account master or readonly key (alias of auth.key) */
/** The account master or readonly key */
key?: string;
/** An object that is used for authenticating requests and must contains one of the options */
auth?: AuthOptions;
/** An object that contains resources tokens.
* Keys for the object are resource Ids and values are the resource tokens.
*/
resourceTokens?: { [resourcePath: string]: string };
/** A user supplied function for resolving header authorization tokens.
* Allows users to generating their own auth tokens, potentially using a separate service
*/
tokenProvider?: TokenProvider;
/** An array of {@link Permission} objects. */
permissionFeed?: PermissionDefinition[];
/** An instance of {@link ConnectionPolicy} class.
* This parameter is optional and the default connectionPolicy will be used if omitted.
*/

Просмотреть файл

@ -1,6 +1,6 @@
import { generateHeaders } from "@azure/cosmos-sign";
import { PermissionDefinition } from "./client";
import { Constants, getResourceIdFromPath, HTTPMethod, ResourceType } from "./common";
import { CosmosClientOptions } from "./CosmosClientOptions";
import { CosmosHeaders } from "./queryExecutionContext";
/** @hidden */
@ -14,54 +14,36 @@ export interface RequestInfo {
export type TokenProvider = (requestInfo: RequestInfo) => Promise<string>;
export interface AuthOptions {
/** Account master key or read only key */
key?: string;
/** The authorization master key to use to create the client. */
masterKey?: string;
/** An object that contains resources tokens.
* Keys for the object are resource Ids and values are the resource tokens.
*/
resourceTokens?: { [resourcePath: string]: string };
/** A user supplied function for resolving header authorization tokens.
* Allows users to generating their own auth tokens, potentially using a separate service
*/
tokenProvider?: TokenProvider;
/** An array of {@link Permission} objects. */
permissionFeed?: PermissionDefinition[];
}
export async function setAuthorizationHeader(
authOptions: AuthOptions,
clientOptions: CosmosClientOptions,
verb: HTTPMethod,
path: string,
resourceId: string,
resourceType: ResourceType,
headers: CosmosHeaders
): Promise<void> {
if (authOptions.permissionFeed) {
authOptions.resourceTokens = {};
for (const permission of authOptions.permissionFeed) {
if (clientOptions.permissionFeed) {
clientOptions.resourceTokens = {};
for (const permission of clientOptions.permissionFeed) {
const id = getResourceIdFromPath(permission.resource);
if (!id) {
throw new Error(`authorization error: ${id} \
is an invalid resourceId in permissionFeed`);
}
authOptions.resourceTokens[id] = (permission as any)._token; // TODO: any
clientOptions.resourceTokens[id] = (permission as any)._token; // TODO: any
}
}
if (authOptions.masterKey || authOptions.key) {
const key = authOptions.masterKey || authOptions.key;
setAuthorizationTokenHeaderUsingMasterKey(verb, resourceId, resourceType, headers, key);
} else if (authOptions.resourceTokens) {
if (clientOptions.key) {
setAuthorizationTokenHeaderUsingMasterKey(verb, resourceId, resourceType, headers, clientOptions.key);
} else if (clientOptions.resourceTokens) {
headers[Constants.HttpHeaders.Authorization] = encodeURIComponent(
getAuthorizationTokenUsingResourceTokens(authOptions.resourceTokens, path, resourceId)
getAuthorizationTokenUsingResourceTokens(clientOptions.resourceTokens, path, resourceId)
);
} else if (authOptions.tokenProvider) {
} else if (clientOptions.tokenProvider) {
headers[Constants.HttpHeaders.Authorization] = encodeURIComponent(
await authOptions.tokenProvider({ verb, path, resourceId, resourceType, headers })
await clientOptions.tokenProvider({ verb, path, resourceId, resourceType, headers })
);
}
}

Просмотреть файл

@ -1,5 +1,6 @@
import { AuthOptions, setAuthorizationHeader } from "../auth";
import { setAuthorizationHeader } from "../auth";
import { Constants, HTTPMethod, jsonStringifyAndEscapeNonASCII, ResourceType } from "../common";
import { CosmosClientOptions } from "../CosmosClientOptions";
import { PartitionKey } from "../documents";
import { CosmosHeaders } from "../queryExecutionContext";
import { FeedOptions, RequestOptions } from "./index";
@ -26,7 +27,7 @@ export function bodyFromData(data: Buffer | string | object) {
}
interface GetHeadersOptions {
authOptions: AuthOptions;
clientOptions: CosmosClientOptions;
defaultHeaders: CosmosHeaders;
verb: HTTPMethod;
path: string;
@ -39,7 +40,7 @@ interface GetHeadersOptions {
}
export async function getHeaders({
authOptions,
clientOptions,
defaultHeaders,
verb,
path,
@ -141,7 +142,7 @@ export async function getHeaders({
headers[Constants.HttpHeaders.PartitionKey] = jsonStringifyAndEscapeNonASCII(partitionKey);
}
if (authOptions.masterKey || authOptions.key || authOptions.tokenProvider) {
if (clientOptions.key || clientOptions.tokenProvider) {
headers[Constants.HttpHeaders.XDate] = new Date().toUTCString();
}
@ -167,13 +168,12 @@ export async function getHeaders({
headers[Constants.HttpHeaders.DisableRUPerMinuteUsage] = true;
}
if (
authOptions.masterKey ||
authOptions.key ||
authOptions.resourceTokens ||
authOptions.tokenProvider ||
authOptions.permissionFeed
clientOptions.key ||
clientOptions.resourceTokens ||
clientOptions.tokenProvider ||
clientOptions.permissionFeed
) {
await setAuthorizationHeader(authOptions, verb, path, resourceId, resourceType, headers);
await setAuthorizationHeader(clientOptions, verb, path, resourceId, resourceType, headers);
}
return headers;
}

Просмотреть файл

@ -11,7 +11,7 @@ import {
import { UserResponse } from "../../dist-esm/client/User/UserResponse";
import { endpoint, masterKey } from "./_testConfig";
const defaultClient = new CosmosClient({ endpoint, auth: { masterKey } });
const defaultClient = new CosmosClient({ endpoint, key: masterKey });
export function addEntropy(name: string): string {
return name + getEntropy();

Просмотреть файл

@ -18,13 +18,13 @@ describe("NodeJS CRUD Tests", function() {
"Should be able to fetch list of databases"
);
const clientOptionsAuthKey = new CosmosClient({ endpoint, auth: { key: masterKey } });
const clientOptionsAuthKey = new CosmosClient({ endpoint, key: masterKey });
assert(
undefined !== (await clientOptionsAuthKey.databases.readAll().fetchAll()),
"Should be able to fetch list of databases"
);
const clientOptionsAuthMasterKey = new CosmosClient({ endpoint, auth: { masterKey } });
const clientOptionsAuthMasterKey = new CosmosClient({ endpoint, key: masterKey });
assert(
undefined !== (await clientOptionsAuthMasterKey.databases.readAll().fetchAll()),
"Should be able to fetch list of databases"
@ -110,7 +110,7 @@ describe("NodeJS CRUD Tests", function() {
const authorizationCRUDTest = async function(isUpsertTest: boolean) {
try {
const badclient = new CosmosClient({ endpoint, auth: undefined });
const badclient = new CosmosClient({ endpoint });
const { resources: databases } = await badclient.databases.readAll().fetchAll();
assert.fail("Must fail");
} catch (err) {
@ -126,7 +126,7 @@ describe("NodeJS CRUD Tests", function() {
resourceTokens[entities.coll1.id] = (entities.permissionOnColl1 as any)._token;
resourceTokens[entities.doc1.id] = (entities.permissionOnColl1 as any)._token;
const col1Client = new CosmosClient({ endpoint, auth: { resourceTokens } });
const col1Client = new CosmosClient({ endpoint, resourceTokens });
// 1. Success-- Use Col1 Permission to Read
const { resource: successColl1 } = await col1Client
@ -209,7 +209,7 @@ describe("NodeJS CRUD Tests", function() {
const resourceTokens: any = {};
resourceTokens[container.id] = (permission as any)._token;
const restrictedClient = new CosmosClient({ endpoint, auth: { resourceTokens } });
const restrictedClient = new CosmosClient({ endpoint, resourceTokens });
await restrictedClient
.database(container.database.id)
.container(container.id)

Просмотреть файл

@ -12,7 +12,7 @@ describe("NodeJS CRUD Tests", function() {
it("nativeApi Client Should throw exception", async function() {
// making timeout 1 ms to make sure it will throw
// (create database request takes 10ms-15ms to finish on emulator)
const client = new CosmosClient({ endpoint, auth: { masterKey }, connectionPolicy: { requestTimeout: 1 } });
const client = new CosmosClient({ endpoint, key: masterKey, connectionPolicy: { requestTimeout: 1 } });
// create database
try {
await getTestDatabase("request timeout", client);
@ -27,7 +27,6 @@ describe("NodeJS CRUD Tests", function() {
it("Accepts node Agent", function() {
const client = new CosmosClient({
endpoint: "https://faaaaaake.com",
auth: { masterKey: "" },
agent: new Agent()
});
assert.ok(client !== undefined, "client shouldn't be undefined if it succeeded");
@ -35,7 +34,7 @@ describe("NodeJS CRUD Tests", function() {
});
describe("Validate user passed AbortController.signal", function() {
it("should throw exception if aborted during the request", async function() {
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
try {
const controller = new AbortController();
const signal = controller.signal;
@ -47,7 +46,7 @@ describe("NodeJS CRUD Tests", function() {
}
});
it("should throw exception if passed an already aborted signal", async function() {
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
try {
const controller = new AbortController();
const signal = controller.signal;

Просмотреть файл

@ -3,7 +3,7 @@ import { CosmosClient, DatabaseDefinition } from "../../dist-esm";
import { endpoint, masterKey } from "../common/_testConfig";
import { addEntropy, removeAllDatabases } from "../common/TestHelpers";
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
describe("NodeJS CRUD Tests", function() {
this.timeout(process.env.MOCHA_TIMEOUT || 10000);

Просмотреть файл

@ -3,7 +3,7 @@ import { CosmosClient } from "../../dist-esm";
import { endpoint, masterKey } from "../common/_testConfig";
import { removeAllDatabases } from "../common/TestHelpers";
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
describe("NodeJS CRUD Tests", function() {
this.timeout(process.env.MOCHA_TIMEOUT || 10000);

Просмотреть файл

@ -3,7 +3,7 @@ import { Constants, CosmosClient } from "../../dist-esm";
import { endpoint, masterKey } from "../common/_testConfig";
import { getTestContainer, removeAllDatabases } from "../common/TestHelpers";
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
const validateOfferResponseBody = function(offer: any) {
assert(offer.id, "Id cannot be null");

Просмотреть файл

@ -4,7 +4,7 @@ import { Container } from "../../dist-esm/client";
import { endpoint, masterKey } from "../common/_testConfig";
import { bulkInsertItems, getTestContainer, getTestDatabase, removeAllDatabases } from "../common/TestHelpers";
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
// TODO: This is required for Node 6 and above, so just putting it in here.
// Might want to decide on only supporting async iterators once Node supports them officially.

Просмотреть файл

@ -65,7 +65,7 @@ describe("Authorization", function() {
const clientReadPermission = new CosmosClient({
endpoint,
auth: { resourceTokens: rTokens }
resourceTokens: rTokens
});
const { resource: coll } = await clientReadPermission
@ -78,7 +78,7 @@ describe("Authorization", function() {
it("Accessing container by permissionFeed", async function() {
const clientReadPermission = new CosmosClient({
endpoint,
auth: { permissionFeed: [collReadPermission] }
permissionFeed: [collReadPermission]
});
// self link must be used to access a resource using permissionFeed
@ -90,7 +90,7 @@ describe("Authorization", function() {
});
it("Accessing container without permission fails", async function() {
const clientNoPermission = new CosmosClient({ endpoint, auth: null });
const clientNoPermission = new CosmosClient({ endpoint });
try {
await clientNoPermission
@ -109,7 +109,7 @@ describe("Authorization", function() {
});
const clientReadPermission = new CosmosClient({
endpoint,
auth: { permissionFeed: [collReadPermission] }
permissionFeed: [collReadPermission]
});
assert.equal("document1", createdDoc.id, "invalid documnet create");
@ -126,7 +126,7 @@ describe("Authorization", function() {
rTokens[container.id] = collAllPermission._token;
const clientAllPermission = new CosmosClient({
endpoint,
auth: { resourceTokens: rTokens }
resourceTokens: rTokens
});
// delete container
@ -139,7 +139,7 @@ describe("Authorization", function() {
it("Modifying container by permissionFeed", async function() {
const clientAllPermission = new CosmosClient({
endpoint,
auth: { permissionFeed: [collAllPermission] }
permissionFeed: [collAllPermission]
});
// self link must be used to access a resource using permissionFeed

Просмотреть файл

@ -12,7 +12,7 @@ import { endpoint, masterKey } from "../common/_testConfig";
let dbAccount: DatabaseAccount;
before(async function() {
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
({ resource: dbAccount } = await client.getDatabaseAccount());
// We reverse the order of the preferred locations list to make sure
// we don't just follow the order we got back from the server
@ -26,7 +26,7 @@ import { endpoint, masterKey } from "../common/_testConfig";
it("Preferred locations should be honored for readEndpoint", async function() {
const client = new CosmosClient({
endpoint,
auth: { masterKey },
key: masterKey,
connectionPolicy: { preferredLocations: PreferredLocations }
});
const currentReadEndpoint = await client.getReadEndpoint();
@ -43,7 +43,7 @@ import { endpoint, masterKey } from "../common/_testConfig";
);
const client = new CosmosClient({
endpoint,
auth: { masterKey },
key: masterKey,
connectionPolicy: {
preferredLocations: PreferredLocations,
useMultipleWriteLocations: true

Просмотреть файл

@ -37,7 +37,7 @@ if (!isBrowser()) {
try {
const client = new CosmosClient({
endpoint,
auth: { masterKey },
key: masterKey,
agent
});
// create database
@ -61,7 +61,7 @@ if (!isBrowser()) {
try {
const client = new CosmosClient({
endpoint,
auth: { masterKey },
key: masterKey,
agent
});
// create database

Просмотреть файл

@ -39,7 +39,7 @@ describe("retry policy tests", function() {
// TODO: need to fix this, the stubbing doesn't work with the new way we work
xit("throttle retry policy test default retryAfter", async function() {
// connectionPolicy.RetryOptions = new RetryOptions(5);
// const client = new CosmosClient({endpoint, auth: { masterKey }, connectionPolicy});
// const client = new CosmosClient({endpoint, key: masterKey, connectionPolicy});
// const { result: db } = await client.createDatabase({ id: "sample database" });
// const { result: collection } = await client.createCollection(db._self, collectionDefinition);
// const originalGetDatabaseAccount = client.getDatabaseAccount;

Просмотреть файл

@ -16,7 +16,7 @@ import { RequestContext } from "../../dist-esm/request/RequestContext";
const client = new CosmosClient({
endpoint,
auth: { masterKey },
key: masterKey,
consistencyLevel: ConsistencyLevel.Session
});
@ -310,7 +310,7 @@ describe("Session Token", function() {
it.skip("client should not have session token of a container created by another client", async function() {
const client2 = new CosmosClient({
endpoint,
auth: { masterKey },
key: masterKey,
consistencyLevel: ConsistencyLevel.Session
});
const database = await getTestDatabase("clientshouldnothaveanotherclienttoken");
@ -333,7 +333,7 @@ describe("Session Token", function() {
it("validate session container update on 'Not found' with 'undefined' status code for non master resource", async function() {
const client2 = new CosmosClient({
endpoint,
auth: { masterKey },
key: masterKey,
consistencyLevel: ConsistencyLevel.Session
});

Просмотреть файл

@ -11,7 +11,7 @@ const masterKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGG
describe.skip("Validate SSL verification check for emulator", function() {
it("nativeApi Client Should throw exception", async function() {
try {
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const client = new CosmosClient({ endpoint, key: masterKey });
// create database
await getTestDatabase("ssl verification", client);
} catch (err) {
@ -24,7 +24,7 @@ describe.skip("Validate SSL verification check for emulator", function() {
it("nativeApi Client Should successfully execute request", async function() {
const client = new CosmosClient({
endpoint,
auth: { masterKey },
key: masterKey,
connectionPolicy: {
disableSSLVerification: true
}

Просмотреть файл

@ -79,7 +79,7 @@ describe("Location Cache", function() {
} preferred region and multi-region write is ${scenario.connectionPolicy.useMultipleWriteLocations}.`, function() {
const connectionPolicy: ConnectionPolicy = scenario.connectionPolicy;
const endpoint = scenario.defaultEndpoint;
const cosmosClientOptions: CosmosClientOptions = { auth: {}, endpoint, connectionPolicy };
const cosmosClientOptions: CosmosClientOptions = { endpoint, connectionPolicy };
const locationCache = new LocationCache(cosmosClientOptions);
before(function() {
@ -289,7 +289,7 @@ describe("Location Cache", function() {
} preferred regions and multi-region write is ${scenario.connectionPolicy.useMultipleWriteLocations}.`, function() {
const connectionPolicy: ConnectionPolicy = scenario.connectionPolicy;
const endpoint = scenario.defaultEndpoint;
const cosmosClientOptions: CosmosClientOptions = { auth: {}, endpoint, connectionPolicy };
const cosmosClientOptions: CosmosClientOptions = { endpoint, connectionPolicy };
const locationCache = new LocationCache(cosmosClientOptions);
if (!scenario.connectionPolicy.useMultipleWriteLocations) {