Skip to content

Commit

Permalink
Merge pull request #17 from xhoms/master
Browse files Browse the repository at this point in the history
bump to version v0.2
  • Loading branch information
xhoms committed Apr 1, 2019
2 parents ab63b50 + 0290c00 commit 11f7c24
Show file tree
Hide file tree
Showing 93 changed files with 6,107 additions and 2,011 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ package-lock.json
secrets.*
example/*js
lib/*js
node_modules/
node_modules/
extras/
9 changes: 9 additions & 0 deletions dist/autocredentials.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { CredentialProviderOptions } from './credentialprovider';
import { DevTokenCredentialsOptions } from './devtokencredentials';
import { Credentials } from './credentials';
import { EntryPoint } from './common';
export declare function autoCredentials(opt?: CredentialProviderOptions & DevTokenCredentialsOptions & {
accessToken?: string;
refreshToken?: string;
entryPoint?: EntryPoint;
}): Promise<Credentials>;
50 changes: 50 additions & 0 deletions dist/autocredentials.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"use strict";
// Copyright 2015-2019 Palo Alto Networks, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
const credentialprovider_1 = require("./credentialprovider");
const devtokencredentials_1 = require("./devtokencredentials");
const credentials_1 = require("./credentials");
const common_1 = require("./common");
const error_1 = require("./error");
const process_1 = require("process");
async function autoCredentials(opt) {
let envClientId = process_1.env['PAN_CLIENT_ID'];
let envClientSecret = process_1.env['PAN_CLIENT_SECRET'];
let envRefreshToken = process_1.env['PAN_REFRESH_TOKEN'];
let envAccessToken = process_1.env['PAN_ACCESS_TOKEN'];
let envEntryPoint = process_1.env['PAN_ENTRYPOINT'];
let entryPoint = 'https://api.us.paloaltonetworks.com';
if (envEntryPoint) {
entryPoint = envEntryPoint;
}
else {
common_1.commonLogger.info({ className: 'AutoCredentials' }, 'Environmental variable PAN_ENTRYPOINT not set. Assuming https://api.us.paloaltonetworks.com');
}
if (!(envAccessToken || (envClientId && envClientSecret && envRefreshToken))) {
common_1.commonLogger.info({ className: 'AutoCredentials' }, 'Neither "PAN_ACCESS_TOKEN" (for static credentials) nor "PAN_CLIENT_ID", "PAN_CLIENT_SECRET" and "PAN_REFRESH_TOKEN" for a memory-based credentials provider where provider. Will try with developer token credetials');
let devTokCredentias = new devtokencredentials_1.DevTokenCredentials(Object.assign({ entryPoint: entryPoint }, opt));
await devTokCredentias.retrieveAccessToken();
return devTokCredentias;
}
if (envClientId && envClientSecret && envRefreshToken) {
common_1.commonLogger.info({ className: 'AutoCredentials' }, 'Using memory based credentials provider');
return credentialprovider_1.defaultCredentialsProviderFactory(Object.assign({ clientId: envClientId, clientSecret: envClientSecret, refreshToken: envRefreshToken, entryPoint: entryPoint }, opt));
}
if (envAccessToken) {
common_1.commonLogger.info({ className: 'AutoCredentials' }, 'Using startic credentials. No refresh available.');
return credentials_1.defaultCredentialsFactory(entryPoint, envAccessToken);
}
throw new error_1.PanCloudError({ className: 'AutoCredentials' }, 'CONFIG', 'Unknown error');
}
exports.autoCredentials = autoCredentials;
43 changes: 23 additions & 20 deletions dist/common.d.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
/**
* Provides common resources for other modules in the pancloud SDK
*/
import { sdkErr } from './error';
import { SdkErr } from './error';
/**
* A pancloud class must provide a className property that will be used to format its log messages
*/
export interface pancloudClass {
export interface PancloudClass {
className: string;
}
export declare enum logLevel {
export declare enum LogLevel {
DEBUG = 0,
INFO = 1,
ALERT = 2,
Expand All @@ -17,12 +17,12 @@ export declare enum logLevel {
/**
* User-provided logger classes are supported as long as they adhere to this interface
*/
export interface pancloudLogger {
level: logLevel;
error(e: sdkErr): void;
alert(source: pancloudClass, message: string, name?: string): void;
info(source: pancloudClass, message: string, name?: string): void;
debug(source: pancloudClass, message: string, name?: string, payload?: any): void;
export interface PancloudLogger {
level: LogLevel;
error(e: SdkErr): void;
alert(source: PancloudClass, message: string, name?: string): void;
info(source: PancloudClass, message: string, name?: string): void;
debug(source: PancloudClass, message: string, name?: string, payload?: any): void;
}
declare const LTYPES: {
"panw.auth": string;
Expand Down Expand Up @@ -51,30 +51,31 @@ declare const LTYPES: {
/**
* Convenience type to guide the developer using the right entry points
*/
export declare type ENTRYPOINT = 'https://api.eu.paloaltonetworks.com' | 'https://api.us.paloaltonetworks.com';
/**
* Convenience type to guide the developer using the right paths
*/
export declare type PATH = "event-service/v1/channels" | "logging-service/v1/queries" | "directory-sync-service/v1";
export declare type EntryPoint = 'https://api.eu.paloaltonetworks.com' | 'https://api.us.paloaltonetworks.com';
export declare const region2EntryPoint: {
[region: string]: EntryPoint;
};
export declare type OAUTH2SCOPE = 'logging-service:read' | 'logging-service:write' | 'event-service:read' | 'directory-sync-service:read';
export declare type ApiPath = "event-service/v1/channels" | "logging-service/v1" | "directory-sync-service/v1";
/**
* Convenience type to guide the developer using the common log types
*/
export declare type LOGTYPE = keyof typeof LTYPES;
export declare function isKnownLogType(t: string): t is LOGTYPE;
export declare type LogType = keyof typeof LTYPES;
export declare function isKnownLogType(t: string): t is LogType;
/**
* Instantiate a module-provided logger at load time
*/
export declare let commonLogger: pancloudLogger;
export declare let commonLogger: PancloudLogger;
/**
* Developer might decide to change the loglevel of the logger object at runtime
* @param newLevel the new log level
*/
export declare function setLogLevel(newLevel: logLevel): void;
export declare function setLogLevel(newLevel: LogLevel): void;
/**
* Changes the common logger variable to a user-provided object
* @param logger user provided pancloudLogger compliant object to be used for SDK logging
*/
export declare function setLogger(logger: pancloudLogger): void;
export declare function setLogger(logger: PancloudLogger): void;
/**
* Abstract function used to retry multiple times a user-provided operation
* @param source class using the retrier. Its className property value will be used in logs generated by the retrier
Expand All @@ -83,5 +84,7 @@ export declare function setLogger(logger: pancloudLogger): void;
* @param handler function that implements the operation
* @param params additional arguments to be passed to the handler function
*/
export declare function retrier<T, O>(source: pancloudClass, n: number | undefined, delay: number | undefined, handler: (...args: T[]) => Promise<O>, ...params: T[]): Promise<O>;
export declare function retrier<T, O>(source: PancloudClass, n: number | undefined, delay: number | undefined, handler: (...args: T[]) => Promise<O>, ...params: T[]): Promise<O>;
export declare function expTokenExtractor(source: PancloudClass, token: string): number;
export declare function uid(): string;
export {};
75 changes: 58 additions & 17 deletions dist/common.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
"use strict";
// Copyright 2015-2019 Palo Alto Networks, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Provides common resources for other modules in the pancloud SDK
*/
Object.defineProperty(exports, "__esModule", { value: true });
var logLevel;
(function (logLevel) {
logLevel[logLevel["DEBUG"] = 0] = "DEBUG";
logLevel[logLevel["INFO"] = 1] = "INFO";
logLevel[logLevel["ALERT"] = 2] = "ALERT";
logLevel[logLevel["ERROR"] = 3] = "ERROR";
})(logLevel = exports.logLevel || (exports.logLevel = {}));
const error_1 = require("./error");
const crypto_1 = require("crypto");
var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
LogLevel[LogLevel["INFO"] = 1] = "INFO";
LogLevel[LogLevel["ALERT"] = 2] = "ALERT";
LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
})(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
const LTYPES = {
"panw.auth": "",
"panw.config": "",
Expand All @@ -34,14 +48,18 @@ const LTYPES = {
"tms.threat": "",
"tms.traps": ""
};
exports.region2EntryPoint = {
'americas': 'https://api.us.paloaltonetworks.com',
'europe': 'https://api.eu.paloaltonetworks.com'
};
function isKnownLogType(t) {
return LTYPES.hasOwnProperty(t);
}
exports.isKnownLogType = isKnownLogType;
/**
* Centralized logging capability for the whole pancloud SDK
*/
class sdkLogger {
class SdkLogger {
/**
*
* @param level only messages with a level equal or avobe this provided value will be loogged
Expand All @@ -52,16 +70,16 @@ class sdkLogger {
this.stackTrace = stackTrace;
}
error(e) {
this.format(e.getSourceClass(), e.getErrorMessage(), logLevel.ERROR, e.name, e.getErrorCode(), undefined, e.stack);
this.format(e.getSourceClass(), e.getErrorMessage(), LogLevel.ERROR, e.name, e.getErrorCode(), undefined, e.stack);
}
alert(source, message, name) {
this.format(source.className, message, logLevel.ALERT, name);
this.format(source.className, message, LogLevel.ALERT, name);
}
info(source, message, name) {
this.format(source.className, message, logLevel.INFO, name);
this.format(source.className, message, LogLevel.INFO, name);
}
debug(source, message, name, payload) {
this.format(source.className, message, logLevel.DEBUG, name, undefined, payload);
this.format(source.className, message, LogLevel.DEBUG, name, undefined, payload);
}
format(source, message, level, name, code, payload, stack) {
if (level >= this.level) {
Expand Down Expand Up @@ -98,12 +116,12 @@ class sdkLogger {
finalOutput += ` payload=${payloadOut}`;
}
switch (level) {
case logLevel.ERROR: {
case LogLevel.ERROR: {
console.error(finalOutput);
break;
}
case logLevel.ALERT:
case logLevel.INFO: {
case LogLevel.ALERT:
case LogLevel.INFO: {
console.info(finalOutput);
break;
}
Expand All @@ -120,7 +138,7 @@ class sdkLogger {
/**
* Instantiate a module-provided logger at load time
*/
exports.commonLogger = new sdkLogger(logLevel.INFO, false);
exports.commonLogger = new SdkLogger(LogLevel.INFO, false);
/**
* Developer might decide to change the loglevel of the logger object at runtime
* @param newLevel the new log level
Expand Down Expand Up @@ -164,3 +182,26 @@ async function retrier(source, n = 3, delay = 100, handler, ...params) {
throw (lastError) ? lastError : new Error('reties exhausted');
}
exports.retrier = retrier;
function expTokenExtractor(source, token) {
let parts = token.split('.');
if (parts.length != 3) {
throw new error_1.PanCloudError(source, 'PARSER', 'Not a valid JWT token format');
}
let expAttribute;
try {
expAttribute = JSON.parse(Buffer.from(parts[1], 'base64').toString()).exp;
}
catch (_a) {
throw new error_1.PanCloudError(source, 'PARSER', 'Not a valid JWT token format');
}
if (typeof expAttribute == 'number') {
return expAttribute;
}
throw new error_1.PanCloudError(source, 'PARSER', 'JWT token does not have a valid "exp" field');
}
exports.expTokenExtractor = expTokenExtractor;
function uid() {
let data = `pancloud${Date.now()}nodejs`;
return crypto_1.createHash('sha1').update(data).digest('base64');
}
exports.uid = uid;
40 changes: 23 additions & 17 deletions dist/core.d.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
/**
* Implements the abstract coreClass that implements common methods for higher-end classes like Event Service
* and Logging Service
*/
import { HttpMethod } from './fetch';
import { Credentials } from './credentials';
import { logLevel } from './common';
export interface coreStats {
import { LogLevel } from './common';
/**
* Core class runtime statistic metrics
*/
export interface CoreStats {
/**
* The number of API transactions completed
*/
apiTransactions: number;
}
/**
* Interface to provide configuration options to the core class
*/
export interface coreOptions {
/**
* credential object that should be used in the coreClass instance
*/
credential: Credentials;
/**
* Toggle the access_token auto-refresh feature
*/
autoRefresh?: boolean;
export interface CoreOptions {
/**
* Minimum level of logs that should be generated by the coreClass
*/
level?: logLevel;
level?: LogLevel;
/**
* Number of times a fetch operation must be retried in case of exception
*/
Expand All @@ -27,13 +30,16 @@ export interface coreOptions {
* Delay (in milliseconds) between retry attempts
*/
retrierDelay?: number;
/**
* If provided, the underlying `fetch` module will use this value as request timeout
*/
fetchTimeout?: number | undefined;
}
/**
* This class should not be used directly. It is meant to be extended. Use higher-level classes like LoggingService
* or EventService
*/
export declare class coreClass {
export declare class CoreClass {
/**
* Credential object to be used by this instance
*/
Expand All @@ -49,17 +55,17 @@ export declare class coreClass {
[i: string]: string;
};
private fetchTimeout;
private autoR;
private retrierCount?;
private retrierDelay?;
lastResponse: any;
className: string;
protected stats: coreStats;
protected stats: CoreStats;
/**
*
* @param cred credentials object instance that will provide the needed JWT access_token
* @param ops configuration options for this instance
*/
protected constructor(baseUrl: string, ops: coreOptions);
protected constructor(cred: Credentials, basePath: string, ops?: CoreOptions);
/**
* Prepares the HTTP headers. Mainly used to keep the Autorization header (bearer access-token)
*/
Expand Down Expand Up @@ -95,5 +101,5 @@ export declare class coreClass {
/**
* Convenience method that abstracts a DELETE operation to the Application Framework
*/
protected void_X_Operation(path?: string, payload?: string, method?: string): Promise<void>;
protected voidXOperation(path?: string, payload?: string, method?: HttpMethod): Promise<void>;
}
Loading

0 comments on commit 11f7c24

Please sign in to comment.