You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gristlabs_grist-core/app/server/lib/DocSession.ts

193 lines
6.7 KiB

import {BrowserSettings} from 'app/common/BrowserSettings';
import {Role} from 'app/common/roles';
import {FullUser} from 'app/common/UserAPI';
import {Document} from 'app/gen-server/entity/Document';
import {ActiveDoc} from 'app/server/lib/ActiveDoc';
(core) support adding user characteristic tables for granular ACLs Summary: This is a prototype for expanding the conditions that can be used in granular ACLs. When processing ACLs, the following variables (called "characteristics") are now available in conditions: * UserID * Email * Name * Access (owners, editors, viewers) The set of variables can be expanded by adding a "characteristic" clause. This is a clause which specifies: * A tableId * The name of an existing characteristic * A colId The effect of the clause is to expand the available characteristics with all the columns in the table, with values taken from the record where there is a match between the specified characteristic and the specified column. Existing clauses are generalized somewhat to demonstrate and test the use these variables. That isn't the main point of this diff though, and I propose to leave generalizing+systematizing those clauses for a future diff. Issues I'm not dealing with here: * How clauses combine. (The scope on GranularAccessRowClause is a hack to save me worrying about that yet). * The full set of matching methods we'll allow. * Refreshing row access in clients when the tables mentioned in characteristic tables change. * Full CRUD permission control. * Default rules (part of combination). * Reporting errors in access rules. That said, with this diff it is possible to e.g. assign a City to editors by their email address or name, and have only rows for those Cities be visible in their client. Ability to modify those rows, and remain updates about them, remains under incomplete control. Test Plan: added tests Reviewers: dsagal Reviewed By: dsagal Differential Revision: https://phab.getgrist.com/D2642
4 years ago
import {Authorizer, getUser, getUserId, RequestWithLogin} from 'app/server/lib/Authorizer';
import {Client} from 'app/server/lib/Client';
/**
* OptDocSession allows for certain ActiveDoc operations to work with or without an open document.
* It is useful in particular for actions when importing a file to create a new document.
*/
export interface OptDocSession {
client: Client|null;
shouldBundleActions?: boolean;
linkId?: number;
browserSettings?: BrowserSettings;
req?: RequestWithLogin;
// special permissions for creating, plugins, system, and share access
mode?: 'nascent'|'plugin'|'system'|'share';
authorizer?: Authorizer;
forkingAsOwner?: boolean; // Set if it is appropriate in a pre-fork state to become an owner.
}
export function makeOptDocSession(client: Client|null, browserSettings?: BrowserSettings): OptDocSession {
if (client && !browserSettings) { browserSettings = client.browserSettings; }
if (client && browserSettings && !browserSettings.locale) { browserSettings.locale = client.locale; }
return {client, browserSettings};
}
/**
* Create an OptDocSession with special access rights.
* - nascent: user is treated as owner (because doc is being created)
* - plugin: user is treated as editor (because plugin access control is crude)
* - system: user is treated as owner (because of some operation bypassing access control)
*/
export function makeExceptionalDocSession(mode: 'nascent'|'plugin'|'system'|'share',
options: {client?: Client,
req?: RequestWithLogin,
browserSettings?: BrowserSettings} = {}): OptDocSession {
const docSession = makeOptDocSession(options.client || null, options.browserSettings);
docSession.mode = mode;
docSession.req = options.req;
return docSession;
}
/**
* Create an OptDocSession from a request. Request should have user and doc access
* middleware.
*/
export function docSessionFromRequest(req: RequestWithLogin): OptDocSession {
return {client: null, req};
}
/**
* DocSession objects maintain information for a single session<->doc instance.
*/
export class DocSession implements OptDocSession {
/**
* Flag to indicate that user actions 'bundle' process is started and in progress (`true`),
* otherwise it's `false`
*/
public shouldBundleActions?: boolean;
/**
* Indicates the actionNum of the previously applied action
* to which the first action in actions should be linked.
* Linked actions appear as one action and can be undone/redone in a single step.
*/
public linkId?: number;
public forkingAsOwner?: boolean;
constructor(
public readonly activeDoc: ActiveDoc,
public readonly client: Client,
public readonly fd: number,
public readonly authorizer: Authorizer
) {}
// Browser settings (like timezone) obtained from the Client.
public get browserSettings(): BrowserSettings { return this.client.browserSettings; }
}
/**
* Extract userId from OptDocSession. Use Authorizer if available (for web socket
* sessions), or get it from the Request if that is available (for rest api calls),
* or from the Client if that is available. Returns null if userId information is
* not available or not cached.
*/
export function getDocSessionUserId(docSession: OptDocSession): number|null {
if (docSession.authorizer) {
return docSession.authorizer.getUserId();
}
if (docSession.req) {
return getUserId(docSession.req);
}
if (docSession.client) {
return docSession.client.getCachedUserId();
}
return null;
}
export function getDocSessionAltSessionId(docSession: OptDocSession): string|null {
if (docSession.req) {
return docSession.req.altSessionId || null;
}
if (docSession.client) {
return docSession.client.getAltSessionId() || null;
}
return null;
}
(core) support adding user characteristic tables for granular ACLs Summary: This is a prototype for expanding the conditions that can be used in granular ACLs. When processing ACLs, the following variables (called "characteristics") are now available in conditions: * UserID * Email * Name * Access (owners, editors, viewers) The set of variables can be expanded by adding a "characteristic" clause. This is a clause which specifies: * A tableId * The name of an existing characteristic * A colId The effect of the clause is to expand the available characteristics with all the columns in the table, with values taken from the record where there is a match between the specified characteristic and the specified column. Existing clauses are generalized somewhat to demonstrate and test the use these variables. That isn't the main point of this diff though, and I propose to leave generalizing+systematizing those clauses for a future diff. Issues I'm not dealing with here: * How clauses combine. (The scope on GranularAccessRowClause is a hack to save me worrying about that yet). * The full set of matching methods we'll allow. * Refreshing row access in clients when the tables mentioned in characteristic tables change. * Full CRUD permission control. * Default rules (part of combination). * Reporting errors in access rules. That said, with this diff it is possible to e.g. assign a City to editors by their email address or name, and have only rows for those Cities be visible in their client. Ability to modify those rows, and remain updates about them, remains under incomplete control. Test Plan: added tests Reviewers: dsagal Reviewed By: dsagal Differential Revision: https://phab.getgrist.com/D2642
4 years ago
/**
* Get as much of user profile as we can (id, name, email).
*/
export function getDocSessionUser(docSession: OptDocSession): FullUser|null {
if (docSession.authorizer) {
return docSession.authorizer.getUser();
}
if (docSession.req) {
const user = getUser(docSession.req);
const email = user.loginEmail;
if (email) {
return {id: user.id, name: user.name, email, ref: user.ref, locale: user.options?.locale};
(core) support adding user characteristic tables for granular ACLs Summary: This is a prototype for expanding the conditions that can be used in granular ACLs. When processing ACLs, the following variables (called "characteristics") are now available in conditions: * UserID * Email * Name * Access (owners, editors, viewers) The set of variables can be expanded by adding a "characteristic" clause. This is a clause which specifies: * A tableId * The name of an existing characteristic * A colId The effect of the clause is to expand the available characteristics with all the columns in the table, with values taken from the record where there is a match between the specified characteristic and the specified column. Existing clauses are generalized somewhat to demonstrate and test the use these variables. That isn't the main point of this diff though, and I propose to leave generalizing+systematizing those clauses for a future diff. Issues I'm not dealing with here: * How clauses combine. (The scope on GranularAccessRowClause is a hack to save me worrying about that yet). * The full set of matching methods we'll allow. * Refreshing row access in clients when the tables mentioned in characteristic tables change. * Full CRUD permission control. * Default rules (part of combination). * Reporting errors in access rules. That said, with this diff it is possible to e.g. assign a City to editors by their email address or name, and have only rows for those Cities be visible in their client. Ability to modify those rows, and remain updates about them, remains under incomplete control. Test Plan: added tests Reviewers: dsagal Reviewed By: dsagal Differential Revision: https://phab.getgrist.com/D2642
4 years ago
}
}
if (docSession.client) {
const id = docSession.client.getCachedUserId();
const ref = docSession.client.getCachedUserRef();
(core) support adding user characteristic tables for granular ACLs Summary: This is a prototype for expanding the conditions that can be used in granular ACLs. When processing ACLs, the following variables (called "characteristics") are now available in conditions: * UserID * Email * Name * Access (owners, editors, viewers) The set of variables can be expanded by adding a "characteristic" clause. This is a clause which specifies: * A tableId * The name of an existing characteristic * A colId The effect of the clause is to expand the available characteristics with all the columns in the table, with values taken from the record where there is a match between the specified characteristic and the specified column. Existing clauses are generalized somewhat to demonstrate and test the use these variables. That isn't the main point of this diff though, and I propose to leave generalizing+systematizing those clauses for a future diff. Issues I'm not dealing with here: * How clauses combine. (The scope on GranularAccessRowClause is a hack to save me worrying about that yet). * The full set of matching methods we'll allow. * Refreshing row access in clients when the tables mentioned in characteristic tables change. * Full CRUD permission control. * Default rules (part of combination). * Reporting errors in access rules. That said, with this diff it is possible to e.g. assign a City to editors by their email address or name, and have only rows for those Cities be visible in their client. Ability to modify those rows, and remain updates about them, remains under incomplete control. Test Plan: added tests Reviewers: dsagal Reviewed By: dsagal Differential Revision: https://phab.getgrist.com/D2642
4 years ago
const profile = docSession.client.getProfile();
if (id && profile) {
return {
id,
ref,
(core) support adding user characteristic tables for granular ACLs Summary: This is a prototype for expanding the conditions that can be used in granular ACLs. When processing ACLs, the following variables (called "characteristics") are now available in conditions: * UserID * Email * Name * Access (owners, editors, viewers) The set of variables can be expanded by adding a "characteristic" clause. This is a clause which specifies: * A tableId * The name of an existing characteristic * A colId The effect of the clause is to expand the available characteristics with all the columns in the table, with values taken from the record where there is a match between the specified characteristic and the specified column. Existing clauses are generalized somewhat to demonstrate and test the use these variables. That isn't the main point of this diff though, and I propose to leave generalizing+systematizing those clauses for a future diff. Issues I'm not dealing with here: * How clauses combine. (The scope on GranularAccessRowClause is a hack to save me worrying about that yet). * The full set of matching methods we'll allow. * Refreshing row access in clients when the tables mentioned in characteristic tables change. * Full CRUD permission control. * Default rules (part of combination). * Reporting errors in access rules. That said, with this diff it is possible to e.g. assign a City to editors by their email address or name, and have only rows for those Cities be visible in their client. Ability to modify those rows, and remain updates about them, remains under incomplete control. Test Plan: added tests Reviewers: dsagal Reviewed By: dsagal Differential Revision: https://phab.getgrist.com/D2642
4 years ago
...profile
};
}
}
return null;
}
/**
* Extract user's role from OptDocSession. Method depends on whether using web
* sockets or rest api. Assumes that access has already been checked by wrappers
* for api methods and that cached access information is therefore available.
*/
export function getDocSessionAccess(docSession: OptDocSession): Role {
// "nascent" DocSessions are for when a document is being created, and user is
// its only owner as yet.
// "system" DocSessions are for access without access control.
if (docSession.mode === 'nascent' || docSession.mode === 'system') { return 'owners'; }
// "plugin" DocSessions are for access from plugins, which is currently quite crude,
// and granted only to editors.
if (docSession.mode === 'plugin') { return 'editors'; }
if (docSession.authorizer) {
const access = docSession.authorizer.getCachedAuth().access;
if (!access) { throw new Error('getDocSessionAccess expected authorizer.getCachedAuth'); }
return access;
}
if (docSession.req) {
const access = docSession.req.docAuth?.access;
if (!access) { throw new Error('getDocSessionAccess expected req.docAuth.access'); }
return access;
}
throw new Error('getDocSessionAccess could not find access information in DocSession');
}
(core) add initial support for special shares Summary: This gives a mechanism for controlling access control within a document that is distinct from (though implemented with the same machinery as) granular access rules. It was hard to find a good way to insert this that didn't dissolve in a soup of complications, so here's what I went with: * When reading rules, if there are shares, extra rules are added. * If there are shares, all rules are made conditional on a "ShareRef" user property. * "ShareRef" is null when a doc is accessed in normal way, and the row id of a share when accessed via a share. There's no UI for controlling shares (George is working on it for forms), but you can do it by editing a `_grist_Shares` table in a document. Suppose you make a fresh document with a single page/table/widget, then to create an empty share you can do: ``` gristDocPageModel.gristDoc.get().docData.sendAction(['AddRecord', '_grist_Shares', null, {linkId: 'xyz', options: '{"publish": true}'}]) ``` If you look at the home db now there should be something in the `shares` table: ``` $ sqlite3 -table landing.db "select * from shares" +----+------------------------+------------------------+--------------+---------+ | id | key | doc_id | link_id | options | +----+------------------------+------------------------+--------------+---------+ | 1 | gSL4g38PsyautLHnjmXh2K | 4qYuace1xP2CTcPunFdtan | xyz | ... | +----+------------------------+------------------------+--------------+---------+ ``` If you take the key from that (gSL4g38PsyautLHnjmXh2K in this case) and replace the document's urlId in its URL with `s.<key>` (in this case `s.gSL4g38PsyautLHnjmXh2K` then you can use the regular document landing page (it will be quite blank initially) or API endpoint via the share. E.g. for me `http://localhost:8080/o/docs/s0gSL4g38PsyautLHnjmXh2K/share-inter-3` accesses the doc. To actually share some material - useful commands: ``` gristDocPageModel.gristDoc.get().docData.getMetaTable('_grist_Views_section').getRecords() gristDocPageModel.gristDoc.get().docData.sendAction(['UpdateRecord', '_grist_Views_section', 1, {shareOptions: '{"publish": true, "form": true}'}]) gristDocPageModel.gristDoc.get().docData.getMetaTable('_grist_Pages').getRecords() gristDocPageModel.gristDoc.get().docData.sendAction(['UpdateRecord', '_grist_Pages', 1, {shareRef: 1}]) ``` For a share to be effective, at least one page needs to have its shareRef set to the rowId of the share, and at least one widget on one of those pages needs to have its shareOptions set to {"publish": "true", "form": "true"} (meaning turn on sharing, and include form sharing), and the share itself needs {"publish": true} on its options. I think special shares are kind of incompatible with public sharing, since by their nature (allowing access to all endpoints) they easily expose the docId, and changing that would be hard. Test Plan: tests added Reviewers: dsagal, georgegevoian Reviewed By: dsagal, georgegevoian Subscribers: jarek, dsagal Differential Revision: https://phab.getgrist.com/D4144
9 months ago
export function getDocSessionShare(docSession: OptDocSession): string|null {
if (docSession.authorizer) {
return docSession.authorizer.getCachedAuth().cachedDoc?.linkId || null;
}
if (docSession.req) {
return docSession.req.docAuth?.cachedDoc?.linkId || null;
}
return null;
}
export function getDocSessionAccessOrNull(docSession: OptDocSession): Role|null {
try {
return getDocSessionAccess(docSession);
} catch (err) {
return null;
}
}
/**
* Get cached information about the document, if available. May be stale.
*/
export function getDocSessionCachedDoc(docSession: OptDocSession): Document|undefined {
return (docSession.req as RequestWithLogin)?.docAuth?.cachedDoc;
}