UNPKG

@cerbos/core

Version:
772 lines 28.1 kB
import { NotOK } from "./errors"; import type { _Method, _Request, _Response, _Service } from "./rpcs"; import type { AccessLogEntry, AddOrUpdatePoliciesRequest, AddOrUpdateSchemasRequest, AuxData, CheckResourceRequest, CheckResourcesRequest, CheckResourcesResponse, CheckResourcesResult, DecisionLogEntry, DeleteSchemasRequest, DeleteSchemasResponse, DisablePoliciesRequest, DisablePoliciesResponse, EnablePoliciesRequest, EnablePoliciesResponse, GetPoliciesRequest, GetPoliciesResponse, GetSchemasRequest, GetSchemasResponse, HealthCheckRequest, HealthCheckResponse, InspectPoliciesRequest, InspectPoliciesResponse, IsAllowedRequest, ListAccessLogEntriesRequest, ListDecisionLogEntriesRequest, ListPoliciesRequest, ListPoliciesResponse, ListSchemasResponse, PlanResourcesRequest, PlanResourcesResponse, Policy, Principal, ReloadStoreRequest, Schema, ServerInfo, ValidationFailedCallback } from "./types/external"; /** @internal */ export declare class _AbortHandler { readonly signal: AbortSignal | undefined; constructor(signal: AbortSignal | undefined); throwIfAborted(): void; onAbort(listener: (error: NotOK) => void): void; error(): NotOK; } /** @internal */ export interface _Transport { unary<Service extends _Service, Method extends _Method<Service, "unary">>(service: Service, method: Method, request: _Request<Service, "unary", Method>, headers: Headers, abortHandler: _AbortHandler): Promise<_Response<Service, "unary", Method>>; serverStream<Service extends _Service, Method extends _Method<Service, "serverStream">>(service: Service, method: Method, request: _Request<Service, "serverStream", Method>, headers: Headers, abortHandler: _AbortHandler): AsyncGenerator<_Response<Service, "serverStream", Method>, void, undefined>; } /** @internal */ export type _Instrumenter = (transport: _Transport) => _Transport; /** @internal */ export declare function _addInstrumenter(instrumenter: _Instrumenter): void; /** @internal */ export declare function _removeInstrumenter(instrumenter: _Instrumenter): void; /** * HTTP headers from which to construct a {@link https://developer.mozilla.org/en-US/docs/Web/API/Headers | Headers} object. * * @public */ export type HeadersInit = [string, string][] | Record<string, string> | Headers; /** * Options for creating a new {@link Client}. * * @public */ export interface Options { /** * Credentials for the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API}. * * @defaultValue `undefined` */ adminCredentials?: AdminCredentials | undefined; /** * Headers to add to every request to the policy decision point. * * @remarks * Headers can be included in the policy decision point's audit logs by setting the `includeMetadataKeys` or `excludeMetadataKeys` fields in the * `audit` {@link https://docs.cerbos.dev/cerbos/latest/configuration/audit | configuration block}. * * The `User-Agent` header is set using {@link Options.userAgent}. * * @defaultValue `undefined` */ headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>) | undefined; /** * Action to take when input fails schema validation. * * @remarks * Possible values are * * - `"throw"`, to throw a {@link ValidationFailed} error; * * - a {@link ValidationFailedCallback} function; or * * - `undefined`, to return the validation errors in the response. * * @defaultValue `undefined` */ onValidationError?: "throw" | ValidationFailedCallback | undefined; /** * Identifier of the playground instance to use when prototyping against the hosted demo policy decision point. * * @defaultValue `undefined` */ playgroundInstance?: string | undefined; /** * Custom user agent to prepend to the built-in value. * * @defaultValue `undefined` */ userAgent?: string | undefined; } /** * Credentials for the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API}. * * @public */ export interface AdminCredentials { /** * Username for authenticating to the admin API. */ username: string; /** * Password for authenticating to the admin API. */ password: string; } /** * Options for sending a request to the policy decision point. * * @public */ export interface RequestOptions { /** * Headers to add to the request. * * @remarks * Headers can be included in the policy decision point's audit logs by setting the `includeMetadataKeys` or `excludeMetadataKeys` fields * in the `audit` {@link https://docs.cerbos.dev/cerbos/latest/configuration/audit | configuration block}. * * The `User-Agent` header is set using {@link Options.userAgent}. * * @defaultValue `undefined` */ headers?: HeadersInit | undefined; /** * A {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | signal} to abort the request. * * @defaultValue `undefined` */ signal?: AbortSignal | undefined; } /** * Base implementation of a client for interacting with the Cerbos policy decision point server. * * @public */ export declare abstract class Client { private readonly transport; private readonly options; /** @internal */ protected constructor(transport: _Transport, options: Options); /** * Add policies, or update existing policies. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, * * - the Cerbos policy decision point server to be configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled, and * * - a dynamic {@link https://docs.cerbos.dev/cerbos/latest/configuration/storage | storage backend}. * * @example * Create a policy in code: * * ```typescript * await cerbos.addOrUpdatePolicies({ * policies: [{ * resourcePolicy: { * resource: "document", * version: "1", * rules: [{ * actions: ["*"], * effect: Effect.ALLOW, * roles: ["ADMIN"], * }], * }, * }], * }); * ``` * * @example * Load a policy from a YAML or JSON file with {@link @cerbos/files#readPolicy}: * * ```typescript * import { readPolicy } from "@cerbos/files"; * * await cerbos.addOrUpdatePolicies({ * policies: [await readPolicy("path/to/policy.yaml")], * }); * ``` * * @example * Load policies and schemas from a directory with {@link @cerbos/files#readDirectory}: * * ```typescript * import { readDirectory } from "@cerbos/files"; * * const { policies, schemas } = await readDirectory("path/to/directory"); * * await cerbos.addOrUpdateSchemas({ schemas }); * await cerbos.addOrUpdatePolicies({ policies }); * ``` */ addOrUpdatePolicies(request: AddOrUpdatePoliciesRequest, options?: RequestOptions): Promise<void>; /** * Add schemas to be used for validating principal or resource attributes, or update existing schemas. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, * * - the Cerbos policy decision point server to be configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled, and * * - a dynamic {@link https://docs.cerbos.dev/cerbos/latest/configuration/storage | storage backend}. * * @example * Create a schema in code: * * ```typescript * * await cerbos.addOrUpdateSchemas({ * schemas: [{ * id: "document.json", * definition: { * type: "object", * properties: { * owner: { type: "string" } * } * }, * }], * }); * ``` * * @example * Load a schema from a JSON file with {@link @cerbos/files#readSchema}: * * ```typescript * import { readSchema } from "@cerbos/files"; * * await cerbos.addOrUpdateSchemas({ * schemas: [await readSchema("_schemas/path/to/schema.json")], * }); * ``` * * @example * Load policies and schemas from a directory with {@link @cerbos/files#readDirectory}: * * ```typescript * import { readDirectory } from "@cerbos/files"; * * const { policies, schemas } = await readDirectory("path/to/directory"); * * await cerbos.addOrUpdateSchemas({ schemas }); * await cerbos.addOrUpdatePolicies({ policies }); * ``` */ addOrUpdateSchemas(request: AddOrUpdateSchemasRequest, options?: RequestOptions): Promise<void>; /** * Checks the health of services provided by the policy decision point server. * * @example * ```typescript * const { status } = await cerbos.checkHealth(); * ``` * * @example * ```typescript * const { status } = await cerbos.checkHealth({ service: Service.ADMIN }); * ``` */ checkHealth(request?: HealthCheckRequest, options?: RequestOptions): Promise<HealthCheckResponse>; /** * Check a principal's permissions on a resource. * * @example * ```typescript * const decision = await cerbos.checkResource({ * principal: { * id: "user@example.com", * roles: ["USER"], * attr: { tier: "PREMIUM" }, * }, * resource: { * kind: "document", * id: "1", * attr: { owner: "user@example.com" }, * }, * actions: ["view", "edit"], * }); * * decision.isAllowed("view"); // => true * ``` */ checkResource(request: CheckResourceRequest, options?: RequestOptions): Promise<CheckResourcesResult>; /** * Check a principal's permissions on a set of resources. * * @example * ```typescript * const decision = await cerbos.checkResources({ * principal: { * id: "user@example.com", * roles: ["USER"], * attr: { tier: "PREMIUM" }, * }, * resources: [ * { * resource: { * kind: "document", * id: "1", * attr: { owner: "user@example.com" }, * }, * actions: ["view", "edit"], * }, * { * resource: { * kind: "image", * id: "1", * attr: { owner: "user@example.com" }, * }, * actions: ["delete"], * }, * ], * }); * * decision.isAllowed({ * resource: { kind: "document", id: "1" }, * action: "view", * }); // => true * ``` */ checkResources(request: CheckResourcesRequest, options?: RequestOptions): Promise<CheckResourcesResponse>; /** * Delete a schema. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, * * - the Cerbos policy decision point (PDP) server to be configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled, and * * - a dynamic {@link https://docs.cerbos.dev/cerbos/latest/configuration/storage | storage backend}. * * The way this method handles failure depends on the version of the connected PDP server. * When the server is running Cerbos v0.25 or later, it returns `true` if the schema was deleted and `false` if the schema was not found. * With earlier versions of Cerbos, it throws an error if the schema was not found, and returns successfully if the schema was deleted; the returned value should be ignored. * * @example * ```typescript * const deleted = await cerbos.deleteSchema("document.json"); * ``` */ deleteSchema(id: string, options?: RequestOptions): Promise<boolean>; /** * Delete multiple schemas. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, * * - the Cerbos policy decision point (PDP) server to be configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled, and * * - a dynamic {@link https://docs.cerbos.dev/cerbos/latest/configuration/storage | storage backend}. * * The way this method handles failure depends on the version of the connected PDP server. * When the server is running Cerbos v0.25 or later, it returns a {@link DeleteSchemasResponse} that includes the number of schemas that were deleted. * With earlier versions of Cerbos, it throws an error if no schemas were found, and returns successfully if at least one schema was deleted; the returned value should be ignored. * * @example * ```typescript * const result = await cerbos.deleteSchemas({ * ids: ["document.json", "image.json"], * }); * ``` */ deleteSchemas(request: DeleteSchemasRequest, options?: RequestOptions): Promise<DeleteSchemasResponse>; /** * Disable multiple policies. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, * * - the Cerbos policy decision point server to be at least v0.25 and configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled, and * * - a dynamic {@link https://docs.cerbos.dev/cerbos/latest/configuration/storage | storage backend}. * * @example * ```typescript * const result = await cerbos.disablePolicies({ * ids: ["resource.document.v1", "resource.image.v1"], * }); * ``` */ disablePolicies(request: DisablePoliciesRequest, options?: RequestOptions): Promise<DisablePoliciesResponse>; /** * Disable a policy. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, * * - the Cerbos policy decision point server to be at least v0.25 and configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled, and * * - a dynamic {@link https://docs.cerbos.dev/cerbos/latest/configuration/storage | storage backend}. * * @example * ```typescript * const disabled = await cerbos.disablePolicy("resource.document.v1"); * ``` */ disablePolicy(id: string, options?: RequestOptions): Promise<boolean>; /** * Enable multiple policies. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, * * - the Cerbos policy decision point server to be at least v0.26 and configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled, and * * - a dynamic {@link https://docs.cerbos.dev/cerbos/latest/configuration/storage | storage backend}. * * @example * ```typescript * const result = await cerbos.enablePolicies({ * ids: ["resource.document.v1", "resource.image.v1"], * }); * ``` */ enablePolicies(request: EnablePoliciesRequest, options?: RequestOptions): Promise<EnablePoliciesResponse>; /** * Enable a policy. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, * * - the Cerbos policy decision point server to be at least v0.26 and configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled, and * * - a dynamic {@link https://docs.cerbos.dev/cerbos/latest/configuration/storage | storage backend}. * * @example * ```typescript * const enabled = await cerbos.enablePolicy("resource.document.v1"); * ``` */ enablePolicy(id: string, options?: RequestOptions): Promise<boolean>; /** * Fetch an access log entry by call ID from the policy decision point server's audit log. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}; and * * - the Cerbos policy decision point server to be configured with * * - the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled * * - the {@link https://docs.cerbos.dev/cerbos/latest/configuration/audit#local | local audit logging backend}, and * * - {@link https://docs.cerbos.dev/cerbos/latest/configuration/audit | access logs} enabled. * * @example * ```typescript * const entry = await cerbos.getAccessLogEntry("01F9VS1N77S83MTSBBX44GYSJ6"); * ``` */ getAccessLogEntry(callId: string, options?: RequestOptions): Promise<AccessLogEntry | undefined>; /** * Fetch a decision log entry by call ID from the policy decision point server's audit log. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}; and * * - the Cerbos policy decision point server to be at least v0.18 and configured with * * - the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled * * - the {@link https://docs.cerbos.dev/cerbos/latest/configuration/audit#local | local audit logging backend}, and * * - {@link https://docs.cerbos.dev/cerbos/latest/configuration/audit | decision logs} enabled. * * @example * ```typescript * const entry = await cerbos.getDecisionLogEntry("01F9VS1N77S83MTSBBX44GYSJ6"); * ``` */ getDecisionLogEntry(callId: string, options?: RequestOptions): Promise<DecisionLogEntry | undefined>; /** * Fetch multiple policies by ID. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, and * * - the Cerbos policy decision point server to be configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled. * * @example * ```typescript * const policies = await cerbos.getPolicies({ * ids: ["resource.document.v1", "resource.image.v1"], * }); * ``` */ getPolicies(request: GetPoliciesRequest, options?: RequestOptions): Promise<GetPoliciesResponse>; /** * Fetch a policy by ID. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, and * * - the Cerbos policy decision point server to be configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled. * * @example * ```typescript * const policy = await cerbos.getPolicy("resource.document.v1"); * ``` */ getPolicy(id: string, options?: RequestOptions): Promise<Policy | undefined>; /** * Fetch a schema by ID. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, and * * - the Cerbos policy decision point server to be configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled. * * @example * ```typescript * const schema = await cerbos.getSchema("document.json"); * ``` */ getSchema(id: string, options?: RequestOptions): Promise<Schema | undefined>; /** * Fetch multiple schemas by ID. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, and * * - the Cerbos policy decision point server to be configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled. * * @example * ```typescript * const schemas = await cerbos.getSchemas({ * ids: ["document.json", "image.json"], * }); * ``` */ getSchemas(request: GetSchemasRequest, options?: RequestOptions): Promise<GetSchemasResponse>; /** * Inspect policies in the store. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}; and * * - the Cerbos policy decision point server to be at least v0.35 and configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled. * * @example * ```typescript * const { policies } = await cerbos.inspectPolicies(); * ``` */ inspectPolicies(request?: InspectPoliciesRequest, options?: RequestOptions): Promise<InspectPoliciesResponse>; /** * Check if a principal is allowed to perform an action on a resource. * * @example * ```typescript * await cerbos.isAllowed({ * principal: { * id: "user@example.com", * roles: ["USER"], * attr: { tier: "PREMIUM" }, * }, * resource: { * kind: "document", * id: "1", * attr: { owner: "user@example.com" }, * }, * action: "view", * }); // => true * ``` */ isAllowed(request: IsAllowedRequest, options?: RequestOptions): Promise<boolean>; /** * List access log entries from the policy decision point server's audit log. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}; and * * - the Cerbos policy decision point server to be configured with * * - the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled * * - the {@link https://docs.cerbos.dev/cerbos/latest/configuration/audit#local | local audit logging backend}, and * * - {@link https://docs.cerbos.dev/cerbos/latest/configuration/audit | access logs} enabled. * * @example * ```typescript * for await (const entry of cerbos.listAccessLogEntries({ filter: { tail: 5 } })) { * console.log(entry); * } * ``` */ listAccessLogEntries(request: ListAccessLogEntriesRequest, options?: RequestOptions): AsyncGenerator<AccessLogEntry, void, undefined>; /** * List decision log entries from the policy decision point server's audit log. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}; and * * - the Cerbos policy decision point server to be configured with * * - the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled * * - the {@link https://docs.cerbos.dev/cerbos/latest/configuration/audit#local | local audit logging backend}, and * * - {@link https://docs.cerbos.dev/cerbos/latest/configuration/audit | decision logs} enabled. * * @example * ```typescript * for await (const entry of cerbos.listDecisionLogEntries({ filter: { tail: 5 } })) { * console.log(entry); * } * ``` */ listDecisionLogEntries(request: ListDecisionLogEntriesRequest, options?: RequestOptions): AsyncGenerator<DecisionLogEntry, void, undefined>; /** * List policies. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, and * * - the Cerbos policy decision point server to be configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled. * * @example * ```typescript * const { ids } = await cerbos.listPolicies(); * ``` */ listPolicies(request?: ListPoliciesRequest, options?: RequestOptions): Promise<ListPoliciesResponse>; /** * List schemas. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, and * * - the Cerbos policy decision point server to be configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API} enabled. * * @example * ```typescript * const { ids } = await cerbos.listSchemas(); * ``` */ listSchemas(options?: RequestOptions): Promise<ListSchemasResponse>; /** * Produce a query plan that can be used to obtain a list of resources on which a principal is allowed to perform a particular action. * * @example * ```typescript * const plan = await cerbos.planResources({ * principal: { * id: "user@example.com", * roles: ["USER"], * attr: { tier: "PREMIUM" }, * }, * resource: { kind: "document" }, * action: "view", * }); * ``` */ planResources(request: PlanResourcesRequest, options?: RequestOptions): Promise<PlanResourcesResponse>; /** * Reload the store. * * @remarks * Requires * * - the client to be configured with {@link Options.adminCredentials}, * * - the Cerbos policy decision point server to be configured with the {@link https://docs.cerbos.dev/cerbos/latest/api/admin_api | admin API}, and * * - a reloadable {@link https://docs.cerbos.dev/cerbos/latest/configuration/storage | storage backend}. * * @example * ```typescript * await cerbos.reloadStore({ wait: true }); * ``` */ reloadStore(request: ReloadStoreRequest, options?: RequestOptions): Promise<void>; /** * Retrieve information about the Cerbos policy decision point server. */ serverInfo(options?: RequestOptions): Promise<ServerInfo>; /** * Create a client instance with a pre-specified principal. */ withPrincipal(principal: Principal, auxData?: Pick<AuxData, "jwt">): ClientWithPrincipal<this>; private unary; private serverStream; private mergeHeaders; private handleValidationErrors; } /** * A client instance with a pre-specified principal. * * @public */ export declare class ClientWithPrincipal<ClientType extends Client = Client> { /** * The client from which this instance was created. */ readonly client: ClientType; /** * The principal for whom this instance was created. */ readonly principal: Principal; /** * Auxiliary data related to the principal for whom this instance was created. * * @defaultValue `{}` */ readonly auxData: Pick<AuxData, "jwt">; /** @internal */ constructor( /** * The client from which this instance was created. */ client: ClientType, /** * The principal for whom this instance was created. */ principal: Principal, /** * Auxiliary data related to the principal for whom this instance was created. * * @defaultValue `{}` */ auxData?: Pick<AuxData, "jwt">); /** * Check the principal's permissions on a resource. * See {@link Client.checkResource} for details. */ checkResource(request: Omit<CheckResourceRequest, "principal">, options?: RequestOptions): Promise<CheckResourcesResult>; /** * Check the principal's permissions on a set of resources. * See {@link Client.checkResources} for details. */ checkResources(request: Omit<CheckResourcesRequest, "principal">, options?: RequestOptions): Promise<CheckResourcesResponse>; /** * Check if the principal is allowed to perform an action on a resource. * See {@link Client.isAllowed} for details. */ isAllowed(request: Omit<IsAllowedRequest, "principal">, options?: RequestOptions): Promise<boolean>; /** * Produce a query plan that can be used to obtain a list of resources on which the principal is allowed to perform a particular action. * See {@link Client.planResources} for details. */ planResources(request: Omit<PlanResourcesRequest, "principal">, options?: RequestOptions): Promise<PlanResourcesResponse>; private merge; } //# sourceMappingURL=client.d.ts.map