Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Readjustement of the introduction image and first version of casbin authorization mechanism #201

Merged
merged 20 commits into from
Nov 28, 2022
Merged
Show file tree
Hide file tree
Changes from 16 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
12 changes: 12 additions & 0 deletions web/backend/model.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# This file define the model of the authorization mechanism
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
1 change: 1 addition & 0 deletions web/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"dependencies": {
"@dedis/kyber": "^3.4.4",
"axios": "^0.24.0",
"casbin": "^5.19.1",
"cookie-parser": "^1.4.6",
"crypto": "^1.0.1",
"express": "^4.17.2",
Expand Down
63 changes: 63 additions & 0 deletions web/backend/policy.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
p, 330383, roles, list
p, 330383, election, create
p, 330383, roles, remove
p, 330383, roles, add
p, 330383, proxies, post
p, 330383, proxies, put
p, 330383, proxies, delete

p, 228271, roles, list
p, 228271, election, create
p, 228271, roles, remove
p, 228271, roles, add
p, 228271, proxies, post
p, 228271, proxies, put
p, 228271, proxies, delete

p, 330361, roles, list
p, 330361, election, create
p, 330361, roles, remove
p, 330361, roles, add
p, 330361, proxies, post
p, 330361, proxies, put
p, 330361, proxies, delete

p, 175129, roles, list
p, 175129, election, create
p, 175129, roles, remove
p, 175129, roles, add
p, 175129, proxies, post
p, 175129, proxies, put
p, 175129, proxies, delete

p, 324610, roles, list
p, 324610, election, create
p, 324610, roles, remove
p, 324610, roles, add
p, 324610, proxies, post
p, 324610, proxies, put
p, 324610, proxies, delete

p, 330382, roles, list
p, 330382, election, create
p, 330382, roles, remove
p, 330382, roles, add
p, 330382, proxies, post
p, 330382, proxies, put
p, 330382, proxies, delete

p, 315822, roles, list
p, 315822, election, create
p, 315822, roles, remove
p, 315822, roles, add
p, 315822, proxies, post
p, 315822, proxies, put
p, 315822, proxies, delete

p, 321016, roles, list
p, 321016, election, create
p, 321016, roles, remove
p, 321016, roles, add
p, 321016, proxies, post
p, 321016, proxies, put
p, 321016, proxies, delete
175 changes: 98 additions & 77 deletions web/backend/src/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,19 @@ import crypto from 'crypto';
import lmdb, { RangeOptions } from 'lmdb';
import xss from 'xss';
import createMemoryStore from 'memorystore';
import { Enforcer, newEnforcer } from 'casbin';

const MemoryStore = createMemoryStore(session);

const ROLES = 'roles';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is way too generic. You should prefix the variable name to indicate how the variable is used:

SUBJECT_ROLES = 'roles';
SUBJECT_PROXIES = 'proxies';
...
ACTION_LIST = 'list';
ACTION_REMOVE = 'remove';
...

const LIST = 'list';
const REMOVE = 'remove';
const ADD = 'add';
const PROXIES = 'proxies';
const PUT = 'put';
const POST = 'post';
const DELETE = 'delete';
const ELECTION = 'election';
const CREATE = 'create';
// store is used to store the session
const store = new MemoryStore({
checkPeriod: 86400000, // prune expired entries every 24h
Expand All @@ -25,6 +35,26 @@ const app = express();

app.use(morgan('tiny'));

let enf: Enforcer;

const enforcerLoading = newEnforcer('model.conf', 'policy.csv');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you need this to be in the global scope, or could you put it (along with the promise resolution below) in an initialization function ?

const port = process.env.PORT || 5000;

Promise.all([enforcerLoading])
.then((res) => {
[enf] = res;
Comment on lines +44 to +46
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you need a Promise.all if you're looking at just one promise resolving?
Why can't you do the following ?

Suggested change
Promise.all([enforcerLoading])
.then((res) => {
[enf] = res;
enforcerLoading
.then((enf) => {

I may be missing something here, so do let me know if I'm wrong 😁

console.log(`🛡 Casbin loaded`);
app.listen(port);
console.log(`🚀 App is listening on port ${port}`);
})
.catch((err) => {
console.error('❌ failed to start:', err);
});

function isAuthorized(sciper: number | undefined, subject: string, action: string): boolean {
return enf.enforceSync(sciper, subject, action);
}

declare module 'express-session' {
export interface SessionData {
userid: number;
Expand Down Expand Up @@ -71,6 +101,7 @@ app.use(express.urlencoded({ extended: true }));

// This endpoint allows anyone to get a "default" proxy. Clients can still use
// the proxy of their choice thought.

app.get('/api/config/proxy', (req, res) => {
res.status(200).send(process.env.DELA_NODE_URL);
});
Expand Down Expand Up @@ -155,48 +186,52 @@ app.post('/api/logout', (req, res) => {
// the react. This endpoint serves to send to the client (actually to react)
// the information of the current user.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment is for the statement bellow, not the setMapAuthorization function, which must also have its own comment describing what it does.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function is hard to understand without any explanation. You should at least describe what contains list: string[][]).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added some comments and while doing it I noticed that the iteration on j isn't necessary.

app.get('/api/personal_info', (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
if (req.session.userid) {
res.json({
sciper: req.session.userid,
lastname: req.session.lastname,
firstname: req.session.firstname,
role: req.session.role,
islogged: true,
});
} else {
res.json({
sciper: 0,
lastname: '',
firstname: '',
role: '',
islogged: false,
});
}
const m = new Map<String, Array<String>>();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you still need this variable?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I decide to delete it

enf.getFilteredPolicy(0, String(req.session.userid)).then((list) => {
for (let i = 0; i < list.length; i += 1) {
for (let j = 1; j < list[0].length; j += +2) {
console.log(list[i][j]);
if (m.has(list[i][j])) {
m.get(list[i][j])?.push(list[i][j + 1]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you really need the ? if you already have called m.has ?
conversely, why not just do m.get and do the push if the result is not null ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even if I check m.has I still have the error (Object is possibly 'undefined') This why I used ?. However it can be a good way to test the result of m.get. I was just wondering how it is better than using ?

} else {
m.set(list[i][j], [list[i][j + 1]]);
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this kind of complex operations probably deserves its own function, that you can write a short test for.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

outside the scope of this PR: would it make sense to memoize this for performance reasons?

console.log(m);
res.set('Access-Control-Allow-Origin', '*');
if (req.session.userid) {
res.json({
sciper: req.session.userid,
lastname: req.session.lastname,
firstname: req.session.firstname,
role: req.session.role,
islogged: true,
authorization: Object.fromEntries(m),
});
} else {
res.json({
sciper: 0,
lastname: '',
firstname: '',
role: '',
islogged: false,
authorization: Object.fromEntries(m),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can just use authorization: new Map<String, Array<String>>(),
or even just authorization: {},

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed !

});
}
});
});

function isAuthorized(roles: string[], req: express.Request): boolean {
if (!req.session || !req.session.userid) {
return false;
}

const { role } = req.session;

return roles.includes(role as string);
}

// ---
// Users role
// ---

// This call allow a user that is admin to get the list of the people that have
// a special role (not a voter).
app.get('/api/user_rights', (req, res) => {
if (!isAuthorized(['admin'], req)) {
if (!isAuthorized(req.session.userid, ROLES, LIST)) {
res.status(400).send('Unauthorized - only admins allowed');
return;
}

const opts: RangeOptions = {};
const users = Array.from(
usersDB.getRange(opts).map(({ key, value }) => ({ id: '0', sciper: key, role: value }))
Expand All @@ -206,13 +241,11 @@ app.get('/api/user_rights', (req, res) => {

// This call (only for admins) allow an admin to add a role to a voter.
app.post('/api/add_role', (req, res) => {
if (!isAuthorized(['admin'], req)) {
if (!isAuthorized(req.session.userid, ROLES, ADD)) {
res.status(400).send('Unauthorized - only admins allowed');
return;
}

// {sciper: xxx, role: xxx}

const { sciper } = req.body;
const { role } = req.body;

Expand All @@ -224,13 +257,12 @@ app.post('/api/add_role', (req, res) => {

// This call (only for admins) allow an admin to remove a role to a user.
app.post('/api/remove_role', (req, res) => {
if (!isAuthorized(['admin'], req)) {
if (!isAuthorized(req.session.userid, ROLES, REMOVE)) {
res.status(400).send('Unauthorized - only admins allowed');
return;
}

const { sciper } = req.body;

usersDB
.remove(sciper)
.then(() => {
Expand All @@ -256,40 +288,12 @@ app.post('/api/remove_role', (req, res) => {
// ---
// Proxies
// ---

const proxiesDB = lmdb.open<string, string>({ path: `${process.env.DB_PATH}proxies` });

app.get('/api/proxies', (req, res) => {
const output = new Map<string, string>();
proxiesDB.getRange({}).forEach((entry) => {
output.set(entry.key, entry.value);
});

res.status(200).json({ Proxies: Object.fromEntries(output) });
});

app.get('/api/proxies/:nodeAddr', (req, res) => {
const { nodeAddr } = req.params;

const proxy = proxiesDB.get(decodeURIComponent(nodeAddr));

if (proxy === undefined) {
res.status(404).send('not found');
return;
}

res.status(200).json({
NodeAddr: nodeAddr,
Proxy: proxy,
});
});

app.post('/api/proxies', (req, res) => {
if (!isAuthorized(['admin', 'operator'], req)) {
if (!isAuthorized(req.session.userid, PROXIES, POST)) {
res.status(400).send('Unauthorized - only admins and operators allowed');
return;
}

try {
const bodydata = req.body;
proxiesDB.put(bodydata.NodeAddr, bodydata.Proxy);
Expand All @@ -301,7 +305,7 @@ app.post('/api/proxies', (req, res) => {
});

app.put('/api/proxies/:nodeAddr', (req, res) => {
if (!isAuthorized(['admin', 'operator'], req)) {
if (!isAuthorized(req.session.userid, PROXIES, PUT)) {
res.status(400).send('Unauthorized - only admins and operators allowed');
return;
}
Expand All @@ -316,7 +320,6 @@ app.put('/api/proxies/:nodeAddr', (req, res) => {
res.status(404).send('not found');
return;
}

try {
const bodydata = req.body;
if (bodydata.Proxy === undefined) {
Expand All @@ -333,7 +336,7 @@ app.put('/api/proxies/:nodeAddr', (req, res) => {
});

app.delete('/api/proxies/:nodeAddr', (req, res) => {
if (!isAuthorized(['admin', 'operator'], req)) {
if (!isAuthorized(req.session.userid, PROXIES, DELETE)) {
res.status(400).send('Unauthorized - only admins and operators allowed');
return;
}
Expand All @@ -358,6 +361,31 @@ app.delete('/api/proxies/:nodeAddr', (req, res) => {
}
});

app.get('/api/proxies', (req, res) => {
const output = new Map<string, string>();
proxiesDB.getRange({}).forEach((entry) => {
output.set(entry.key, entry.value);
});

res.status(200).json({ Proxies: Object.fromEntries(output) });
});

app.get('/api/proxies/:nodeAddr', (req, res) => {
const { nodeAddr } = req.params;

const proxy = proxiesDB.get(decodeURIComponent(nodeAddr));

if (proxy === undefined) {
res.status(404).send('not found');
return;
}

res.status(200).json({
NodeAddr: nodeAddr,
Proxy: proxy,
});
});

// ---
// end of proxies
// ---
Expand Down Expand Up @@ -461,12 +489,10 @@ function sendToDela(dataStr: string, req: express.Request, res: express.Response

// Secure /api/evoting to admins and operators
app.use('/api/evoting/*', (req, res, next) => {
if (!isAuthorized(['admin', 'operator'], req)) {
console.log('role is:', req.session.role);
if (!isAuthorized(req.session.userid, ELECTION, CREATE)) {
res.status(400).send('Unauthorized - only admins and operators allowed');
return;
}

next();
});

Expand Down Expand Up @@ -557,8 +583,3 @@ app.get('*', (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
res.status(404).send(`not found ${xss(url.toString())}`);
});

const port = process.env.PORT || 5000;
app.listen(port);

console.log(`App is listening on port ${port}`);
2 changes: 2 additions & 0 deletions web/backend/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
}
},
"include": [
"model.conf",
"policy.csv",
"src/Server.ts",
"config.json"
],
Expand Down
Loading