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 17 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
180 changes: 103 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 @@ -154,49 +185,58 @@ app.post('/api/logout', (req, res) => {
// As the user is logged on the app via this express but must also be logged in
// 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,
});
}
});

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

Choose a reason for hiding this comment

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

in typescript it's good to explicitly indicate the return type.

Suggested change
function setMapAuthorization(list: string[][]) {
function setMapAuthorization(list: string[][]): Map<string, Array<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.

Done !

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 want to use String the object or just string the plain data type?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

When searching which one use, I found that it is better to avoid bugs to use string

for (let i = 0; i < list.length; i += 1) {
for (let j = 1; j < list[0].length; j += +2) {
Copy link
Contributor

Choose a reason for hiding this comment

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

you should explain (1) what is contained in list[0], and (2) why you are doing += 2.

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 delete that.

console.log(list[i][j]);
Copy link
Contributor

Choose a reason for hiding this comment

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

you probably used it for debugging. To be removed.

if (m.has(list[i][j])) {
m.get(list[i][j])?.push(list[i][j + 1]);
} else {
m.set(list[i][j], [list[i][j + 1]]);
}
}
}

const { role } = req.session;

return roles.includes(role as string);
console.log(m);
return m;
}
app.get('/api/personal_info', (req, res) => {
let m = new Map<String, Array<String>>();
enf.getFilteredPolicy(0, String(req.session.userid)).then((list) => {
m = setMapAuthorization(list);
Copy link
Contributor

Choose a reason for hiding this comment

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

If the user is not logged you can avoid calling setMapAuthorization and return an empty map.

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 !

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 !

});
}
});
});

// ---
// 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 +246,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 +262,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 +293,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 +310,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 +325,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 +341,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 +366,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 +494,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 +588,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