Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions orga/changelog/fix-stream-fresh-auth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- FIX `/pullStream` of the replication endpoint and `/query/observe` of the REST endpoint loaded the current auth data before each event but still filtered the documents by the auth data of the connect, so a client kept getting documents it had lost access to [#482](https://github.com/pubkey/rxdb-server/pull/482)
12 changes: 11 additions & 1 deletion src/plugins/server/endpoint-replication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,6 @@ export class RxServerReplicationEndpoint<ServerAppType, AuthType, RxDocType> imp
}

adapter.setSSEHeaders(res);
const docDataMatcherStream = getDocAllowedMatcher(this, ensureNotFalsy(authData));
const subscription = replicationHandler.masterChangeStream$.pipe(
concatMap(async (changes) => {
/**
Expand All @@ -256,6 +255,17 @@ export class RxServerReplicationEndpoint<ServerAppType, AuthType, RxDocType> imp
if (changes === 'RESYNC') {
return changes;
} else {
/**
* The auth data can be different from the one of the connect,
* so the documents must be filtered by the current auth data.
*/
let docDataMatcherStream: (docData: any) => boolean;
try {
docDataMatcherStream = getDocAllowedMatcher(this, authData);
} catch (err) {
// the queryModifier does not allow this auth data, so end the stream
return null;
}
const useDocs = changes.documents.filter(d => docDataMatcherStream(d as any));
return {
documents: useDocs,
Expand Down
17 changes: 15 additions & 2 deletions src/plugins/server/endpoint-rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,6 @@ export class RxServerRestEndpoint<ServerAppType, AuthType, RxDocType> implements
const rxQuery = this.collection.find(useQuery as any);
const subscription = rxQuery.$.pipe(
concatMap(async (result) => {
const resultData = result.map(doc => removeServerOnlyFields(doc.toJSON()));

/**
* The auth-data might be expired
Expand All @@ -186,7 +185,21 @@ export class RxServerRestEndpoint<ServerAppType, AuthType, RxDocType> implements
return null;
}

return resultData;
/**
* The auth data can be different from the one of the connect,
* so the results must be filtered by the current auth data.
*/
let docMatcher: (docData: any) => boolean;
try {
docMatcher = getDocAllowedMatcher(this, ensureNotFalsy(authData));
} catch (err) {
// the queryModifier does not allow this auth data, so end the stream
return null;
}
return result
.map(doc => doc.toJSON())
.filter(docData => docMatcher(docData as any))
.map(docData => removeServerOnlyFields(docData));
}),
takeWhile(f => f !== null),
tap({ complete: () => adapter.endResponse(res) }),
Expand Down
81 changes: 81 additions & 0 deletions test/unit/endpoint-replication.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -909,6 +909,87 @@ describe('endpoint-replication.test.ts', () => {
serverCol.database.close();
clientCol.database.close();
});
it('should use the current auth data to filter the events of an open pullStream', async () => {
const serverCol = await humansCollection.create(0);
let currentUserId = headers.userid;
const port = await nextPort();
const server = await createRxServer({
adapter: TEST_SERVER_ADAPTER,
database: serverCol.database,
authHandler: () => ({
validUntil: Date.now() + 100000,
data: { userid: currentUserId }
}),
port
});
const endpoint = await server.addReplicationEndpoint({
name: randomToken(10),
collection: serverCol,
queryModifier
});
await server.start();

const events: any[] = [];
const eventSource = new EventSource('http://localhost:' + port + '/' + endpoint.urlPath + '/pullStream', {
fetch: customFetchWithFixedHeaders(headers)
});
eventSource.onmessage = event => events.push(JSON.parse(event.data));
const hasDoc = (id: string) => events.some(e => e.documents && e.documents.some((d: any) => d.passportId === id));
await waitUntil(() => eventSource.readyState === EventSource.OPEN);

await serverCol.insert(schemaObjects.humanData('before-change', 1, headers.userid));
await waitUntil(() => hasDoc('before-change'));

// the user has no longer access to the documents of the old userid
currentUserId = 'bob';
await serverCol.insert(schemaObjects.humanData('after-change', 1, headers.userid));
await serverCol.insert(schemaObjects.humanData('bob-doc', 1, 'bob'));
await waitUntil(() => hasDoc('bob-doc'));
assert.strictEqual(hasDoc('after-change'), false);

eventSource.close();
await serverCol.database.close();
});
it('should end the pullStream when the queryModifier throws for the current auth data', async () => {
const serverCol = await humansCollection.create(0);
let currentUserId = headers.userid;
const port = await nextPort();
const server = await createRxServer({
adapter: TEST_SERVER_ADAPTER,
database: serverCol.database,
authHandler: () => ({
validUntil: Date.now() + 100000,
data: { userid: currentUserId }
}),
port
});
const endpoint = await server.addReplicationEndpoint({
name: randomToken(10),
collection: serverCol,
queryModifier: (authData, query) => {
if (authData.data.userid === 'blocked-user') {
throw new Error('user is blocked');
}
return queryModifier(authData, query);
}
});
await server.start();

let errored = false;
const eventSource = new EventSource('http://localhost:' + port + '/' + endpoint.urlPath + '/pullStream', {
fetch: customFetchWithFixedHeaders(headers)
});
eventSource.onerror = () => errored = true;
await waitUntil(() => eventSource.readyState === EventSource.OPEN);

currentUserId = 'blocked-user';
await serverCol.insert(schemaObjects.humanData('after-block', 1, headers.userid));
// the server must end the stream instead of crashing
await waitUntil(() => errored);

eventSource.close();
await serverCol.database.close();
});
it('should only accept the matching documents on the server', async () => {
const serverCol = await humansCollection.create(0);
const port = await nextPort();
Expand Down
36 changes: 36 additions & 0 deletions test/unit/endpoint-rest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,42 @@ describe('endpoint-rest.test.ts', () => {

await col.database.close();
});
it('should use the current auth data to filter the results of an open stream', async () => {
const col = await humansCollection.create(0);
await col.insert(schemaObjects.humanData('alice-doc', 1, headers.userid));
let currentUserId = headers.userid;
const port = await nextPort();
const server = await createRxServer({
adapter: TEST_SERVER_ADAPTER,
database: col.database,
authHandler: () => ({
validUntil: Date.now() + 100000,
data: { userid: currentUserId }
}),
port
});
const endpoint = await server.addRestEndpoint({
name: randomToken(10),
collection: col,
queryModifier
});
await server.start();
const client = createRestClient<HumanDocumentType>('http://localhost:' + port + '/' + endpoint.urlPath, headers);

const emitted: HumanDocumentType[][] = [];
const sub = client.observeQuery({ selector: {} }).subscribe(result => emitted.push(result));
await waitUntil(() => emitted.length === 1);
assert.deepStrictEqual(ensureNotFalsy(emitted[0]).map(d => d.passportId), ['alice-doc']);

// the user has no longer access to the documents of the old userid
currentUserId = 'bob';
await col.insert(schemaObjects.humanData('alice-doc-2', 1, headers.userid));
await waitUntil(() => emitted.length === 2);
assert.deepStrictEqual(ensureNotFalsy(lastOfArray(emitted)), []);

sub.unsubscribe();
await col.database.close();
});
it('should stop observing on the server when the client unsubscribes', async () => {
const col = await humansCollection.create(1);
const port = await nextPort();
Expand Down
Loading