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 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
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
184 changes: 107 additions & 77 deletions web/backend/src/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,20 @@ 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 SUBJECT_ROLES = 'roles';
const SUBJECT_PROXIES = 'proxies';
const SUBJECT_ELECTION = 'election';

const ACTION_LIST = 'list';
const ACTION_ACTION_REMOVE = 'remove';
const ACTION_ADD = 'add';
const ACTION_PUT = 'put';
const ACTION_POST = 'post';
const ACTION_DELETE = 'delete';
const ACTION_CREATE = 'create';
// store is used to store the session
const store = new MemoryStore({
checkPeriod: 86400000, // prune expired entries every 24h
Expand All @@ -25,6 +36,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 +102,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 @@ -151,52 +183,64 @@ app.post('/api/logout', (req, res) => {
});
});

// This function helps us convert the double list of the authorization
// returned by the casbin function getFilteredPolicy to a map that link
// an object to the action authorized
// list[0] contains the policies so list[i][0] is the sciper
// list[i][1] is the subject and list[i][2] is the action
function setMapAuthorization(list: string[][]): Map<String, Array<String>> {
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) {
const subject = list[i][1];
const action = list[i][2];
if (m.has(subject)) {
m.get(subject)?.push(action);
} else {
m.set(subject, [action]);
}
}
console.log(m);
return m;
}

// 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.
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,
});
}
enf.getFilteredPolicy(0, String(req.session.userid)).then((list) => {
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(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.

much cleaner :)

});
} else {
res.json({
sciper: 0,
lastname: '',
firstname: '',
role: '',
islogged: false,
authorization: {},
});
}
});
});

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, SUBJECT_ROLES, ACTION_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 +250,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, SUBJECT_ROLES, ACTION_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 +266,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, SUBJECT_ROLES, ACTION_ACTION_REMOVE)) {
res.status(400).send('Unauthorized - only admins allowed');
return;
}

const { sciper } = req.body;

usersDB
.remove(sciper)
.then(() => {
Expand All @@ -256,40 +297,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, SUBJECT_PROXIES, ACTION_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 +314,7 @@ app.post('/api/proxies', (req, res) => {
});

app.put('/api/proxies/:nodeAddr', (req, res) => {
if (!isAuthorized(['admin', 'operator'], req)) {
if (!isAuthorized(req.session.userid, SUBJECT_PROXIES, ACTION_PUT)) {
res.status(400).send('Unauthorized - only admins and operators allowed');
return;
}
Expand All @@ -316,7 +329,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 +345,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, SUBJECT_PROXIES, ACTION_DELETE)) {
res.status(400).send('Unauthorized - only admins and operators allowed');
return;
}
Expand All @@ -358,6 +370,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 +498,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, SUBJECT_ELECTION, ACTION_CREATE)) {
res.status(400).send('Unauthorized - only admins and operators allowed');
return;
}

next();
});

Expand Down Expand Up @@ -557,8 +592,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}`);
Loading