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 13 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, database, removerole
p, 330383, database, addrole
p, 330383, proxies, post
p, 330383, proxies, put
p, 330383, proxies, delete

p, 228271, roles, list
p, 228271, election, create
p, 228271, database, removerole
p, 228271, database, addrole
p, 228271, proxies, post
p, 228271, proxies, put
p, 228271, proxies, delete

p, 330361, roles, list
p, 330361, election, create
p, 330361, database, removerole
p, 330361, database, addrole
p, 330361, proxies, post
p, 330361, proxies, put
p, 330361, proxies, delete

p, 175129, roles, list
p, 175129, election, create
p, 175129, database, removerole
p, 175129, database, addrole
p, 175129, proxies, post
p, 175129, proxies, put
p, 175129, proxies, delete

p, 324610, roles, list
p, 324610, election, create
p, 324610, database, removerole
p, 324610, database, addrole
p, 324610, proxies, post
p, 324610, proxies, put
p, 324610, proxies, delete

p, 330382, roles, list
p, 330382, election, create
p, 330382, database, removerole
p, 330382, database, addrole
p, 330382, proxies, post
p, 330382, proxies, put
p, 330382, proxies, delete

p, 315822, roles, list
p, 315822, election, create
p, 315822, database, removerole
p, 315822, database, addrole
p, 315822, proxies, post
p, 315822, proxies, put
p, 315822, proxies, delete

p, 321016, roles, list
p, 321016, election, create
p, 321016, database, removerole
p, 321016, database, addrole
p, 321016, proxies, post
p, 321016, proxies, put
p, 321016, proxies, delete
137 changes: 78 additions & 59 deletions web/backend/src/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ 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);

Expand All @@ -25,6 +26,27 @@ 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 e = 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.

this looks unused

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 @@ -175,28 +197,29 @@ app.get('/api/personal_info', (req, res) => {
}
});

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

const { role } = req.session;
// const { role } = req.session;

return roles.includes(role as string);
}
// return roles.includes(role as string);
// }
Copy link
Contributor

Choose a reason for hiding this comment

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

feel free to delete code that is not relevant anymore. Commented out code is generally frowned upon 😄


// const e = newEnforcer('model.conf', 'policy.csv');

// ---
// 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 +229,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, 'database', 'addrole')) {
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 +245,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, 'database', 'removerole')) {
res.status(400).send('Unauthorized - only admins allowed');
return;
}

const { sciper } = req.body;

usersDB
.remove(sciper)
.then(() => {
Expand All @@ -256,40 +276,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,9 +293,8 @@ 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;
}

let { nodeAddr } = req.params;
Expand All @@ -316,7 +307,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,9 +323,8 @@ 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;
}

let { nodeAddr } = req.params;
Expand All @@ -358,6 +347,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,13 +475,18 @@ 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);
res.status(400).send('Unauthorized - only admins and operators allowed');
return;
}

next();
e.then((enforcer) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

is there are a reason not to use isAuthorized here?

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 just forget it. It is fixed !

enforcer
.enforce(req.session.userid, 'election', 'create')
.then((isOk) => {
if (isOk) {
next();
} else {
res.status(400).send('Unauthorized - only admins and operators allowed');
}
})
.catch((error) => console.log('error', error));
}).catch((error1) => console.log('error', error1));
Copy link
Contributor

Choose a reason for hiding this comment

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

As per our discussion today, this should work:

Suggested change
e.then((enforcer) => {
enforcer
.enforce(req.session.userid, 'election', 'create')
.then((isOk) => {
if (isOk) {
next();
} else {
res.status(400).send('Unauthorized - only admins and operators allowed');
}
})
.catch((error) => console.log('error', error));
}).catch((error1) => console.log('error', error1));
e.then((enforcer) => {
return enforcer
.enforce(req.session.userid, 'election', 'create')
.then((isOk) => {
if (isOk) {
next();
} else {
res.status(400).send('Unauthorized - only admins and operators allowed');
}
})
}).catch((error) => console.log('error', error));

No need to do a double-catch 😁
And since you're directly returning a value, you could also do this (notice the absence of {} and return):

Suggested change
e.then((enforcer) => {
enforcer
.enforce(req.session.userid, 'election', 'create')
.then((isOk) => {
if (isOk) {
next();
} else {
res.status(400).send('Unauthorized - only admins and operators allowed');
}
})
.catch((error) => console.log('error', error));
}).catch((error1) => console.log('error', error1));
e.then((enforcer) =>
enforcer
.enforce(req.session.userid, 'election', 'create')
.then((isOk) => {
if (isOk) {
next();
} else {
res.status(400).send('Unauthorized - only admins and operators allowed');
}
})).catch((error) => console.log('error', error));

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 modify that using the proposition of Noemien.

});

// https://stackoverflow.com/a/1349426
Expand Down Expand Up @@ -558,7 +577,7 @@ app.get('*', (req, res) => {
res.status(404).send(`not found ${xss(url.toString())}`);
});

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

console.log(`App is listening on port ${port}`);
// console.log(`App is listening on port ${port}`);
Copy link
Contributor

Choose a reason for hiding this comment

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

feel free to delete code, no need to comment it out 😁

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