SlideShare une entreprise Scribd logo
1  sur  38
Télécharger pour lire hors ligne
Take Data Validation
Seriously
Paul Milham, WildWorks
WildWorks
Animal Jam
Outline
• Attacks
• Data Validation => Security
• Data Normalization => Stability
• Joi
• Tean
• Express Integration
• Hapi Integration
• Questions
Safety
• My job is to keep kids safe.
• How do we keep our application safe?
• Safe from what?
Attacks
• The web is full of jerks
• https://www.owasp.org/index.php/Category:Attack
• Read that for a bedtime horror story
SQL Injection
console.log(name); // paul
console.log(email); // '); DROP TABLE db.user; --
mysql.query(`INSERT INTO db.user (name, email) VALUES ('${name}', '${email}')`);
Shell Injection
console.log(pass); // "; rm -rf /"
require("child_process").exec(`
php -r "print crypt('${pass}','$1$rounds=1$salt$');"
`, (err, stdout, stderr) => {
});
// hopefully you're using containers
ReDOS
const msg = 'foo=bar' + ';'.repeat(65535) + 'domain=example.com';
console.time("regex");
console.log(msg.search(/;+$/));
console.timeEnd("regex"); // regex: 5854.071ms :(
• This is a sample vulnerability in tough cookie
• https://snyk.io/vuln/npm:tough-cookie:20160722
• Be careful of "evil" regex
Security
• It’s a scary world
• Security is important
• There’s a lot more than just those three
Validation
• Verify the shape of the data
• Malicious data can’t get in
• First line of defense
Simple Joi
"use strict";
const Joi = require("joi");
Joi.validate("srsly a string", Joi.string(), (err, value) => {
console.log(err); // null
console.log(value); // "srsly a string"
});
Joi Failure
Joi.validate(5, Joi.string(), (err, value) => {
console.log(err); // Error
console.log(value); // 5
});
Joi Schema
const schema = Joi.object().keys({
username: Joi.string().email({tldWhiteList: ["wildworks"]}).required(),
password: Joi.string().min(6).max(25).required(),
});
Joi.validate({
username: "paul.milham@wildworks.com",
password: "justinbieber",
}, schema, (err, value) => {
console.log(err);
console.log(value);
});
All In
const schema = Joi.object().keys({
username: Joi.string().email({tldWhiteList: ["wildworks"]}).required(),
});
Joi.validate({
username: "paul.milham@wildworks.com",
password: "justinbieber",
}, schema, (err, value) => {
console.log(err); // justinbieber is not allowed
});
All In
• Validating one field means validating them all
• Hard for devs to forget
Data Normalization
• Normalization is being a good citizen
• Normalization creates a contract with your consumer
• Normalization goes a lot deeper than this (we'll get to that later)
Joi Conversion
Joi.validate("1.916", Joi.number(), (err, value) => {
console.log(value.toFixed(1)); // 1.9 (No TypeError!)
});
Joi Defaults
Joi.validate(undefined, Joi.number().default(0), (err, value) => {
console.log(value.toFixed(1)); // 0.0 (No TypeError!)
});
Tean
•Declarative syntax (schemas are POJOs)
•Async
•Convert data into models
•Strict by default
•https://www.npmjs.com/package/tean
•Note that custom validators were recently added to Joi
Tean Validation
// simple validation
tean.object({animal: "string"}, {animal: “kangaroo”},
(isValid, result) => {
console.log(isValid); // true
console.log(result); // {animal: "kangaroo"}
});
Tean Failure
tean.object({animal: "string"}, {animal: null}, (isValid, result) => {
console.log(isValid); // false
console.log(result); // ["animal (null) is not a string"]
});
Tean Normalization
// optional parameters
tean.object({animal: “string(kangaroo,tiger)=tiger”, sparkles: "bool=true"}, {animal: "tiger"},
(isValid, result) => {
console.log(isValid); // true
console.log(result); // {animal: "tiger", sparkles: true}
// Note that the original object is not altered! Normalized and validated data is passed into
"result" in the callback
});
Model Mapping
tean.object(req.body.params, {
accessory: "avatarAccessory",
user: ["userUid"],
}, (isValid, result) => {
});
Data Normalization
• Provides a friendly API
• Provides consistency and reliability
• Eliminates lots of common bugs
Express
• Everyone uses it!
• No built in validation!
• Too many exclamation points!
• https://expressjs.com/
Express + Joi
app.get('/:username', function (req, res) {
const schema = Joi.object().keys({
username: Joi.string().required(),
});
Joi.validate(req.params, schema, (err, value) => {
console.log(err);
req.params = value;
res.send(`${req.params.username} is the best!`);
});
});
Express + Tean
app.get('/:user', function (req, res) {
tean.object(req.body.params, {
user: "userUid",
}, (isValid, result) => {
console.log(isValid);
req.params = result;
res.send(`${result.user.name} is the best!`);
});
});
Problem
• We’re relying on the developer to remember to validate
• This is a problem for maintenance and updates
• Middleware to the rescue!
Route Middleware
this.app.post(options.route,
tean.expressRequest(options.paramMap),
(req, res) => {
// do stuff
options.handler(req.safeData, req, res);
},
(err, req, res) => {
console.log(err.stack);
res.status(500).send();
}
);
Express + Joi
• https://www.npmjs.com/package/celebrate
Hapi
• Hapi isn't minimalist like Express
• Lots of options out of the box
• http://hapijs.com/
Hapi Validation
app.route({
method: "POST",
path: "/",
config: {
handler: (req, reply) => {
reply("hey!");
},
validate: {
payload: {
username: Joi.string().email().required(),
password: Joi.string().max(25).required(),
},
},
},
});
Take Away
• FORCE validation of data - an opt in system isn't good enough
• Make sure shape of data is acceptable
• No validation, no data
• This ensures malicious data does not enter your application
Take Away
• FORCE normalization of data shape
• Data should always have a consistent shape
• Make data access and usage reliable
• Eliminates lots of “stupid” bugs
On the Way Out
• Have you thought about data security on the way out?
• Mind blown!
• Prevent Data Leaks from "heartbleed" or SQL Injection
• Provide same stability contract for your client app
Thanks!
• Any questions?
• @domrein

Contenu connexe

Tendances

Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6Technopark
 
SilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringSilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringIngo Schommer
 
Web осень 2012 лекция 6
Web осень 2012 лекция 6Web осень 2012 лекция 6
Web осень 2012 лекция 6Technopark
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practicesmanugoel2003
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Konstantin Kudryashov
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitPeter Wilcsinszky
 
My Top 5 APEX JavaScript API's
My Top 5 APEX JavaScript API'sMy Top 5 APEX JavaScript API's
My Top 5 APEX JavaScript API'sRoel Hartman
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowKacper Gunia
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
Getting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingGetting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingMark Rickerby
 
Using Task Queues and D3.js to build an analytics product on App Engine
Using Task Queues and D3.js to build an analytics product on App EngineUsing Task Queues and D3.js to build an analytics product on App Engine
Using Task Queues and D3.js to build an analytics product on App EngineRiver of Talent
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2Kacper Gunia
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupHenrik Engström
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Kacper Gunia
 
Windows Server 2008 (PowerShell Scripting Uygulamaları)
Windows Server 2008 (PowerShell Scripting Uygulamaları)Windows Server 2008 (PowerShell Scripting Uygulamaları)
Windows Server 2008 (PowerShell Scripting Uygulamaları)ÇözümPARK
 

Tendances (20)

Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6
 
SilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringSilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript Refactoring
 
Web осень 2012 лекция 6
Web осень 2012 лекция 6Web осень 2012 лекция 6
Web осень 2012 лекция 6
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
 
My Top 5 APEX JavaScript API's
My Top 5 APEX JavaScript API'sMy Top 5 APEX JavaScript API's
My Top 5 APEX JavaScript API's
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Getting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingGetting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe Testing
 
Using Task Queues and D3.js to build an analytics product on App Engine
Using Task Queues and D3.js to build an analytics product on App EngineUsing Task Queues and D3.js to build an analytics product on App Engine
Using Task Queues and D3.js to build an analytics product on App Engine
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Windows Server 2008 (PowerShell Scripting Uygulamaları)
Windows Server 2008 (PowerShell Scripting Uygulamaları)Windows Server 2008 (PowerShell Scripting Uygulamaları)
Windows Server 2008 (PowerShell Scripting Uygulamaları)
 

En vedette

Hitchhiker's Guide to"'Serverless" Javascript - Steven Faulkner, Bustle
Hitchhiker's Guide to"'Serverless" Javascript - Steven Faulkner, BustleHitchhiker's Guide to"'Serverless" Javascript - Steven Faulkner, Bustle
Hitchhiker's Guide to"'Serverless" Javascript - Steven Faulkner, BustleNodejsFoundation
 
State of the CLI- Kat Marchan
State of the CLI- Kat MarchanState of the CLI- Kat Marchan
State of the CLI- Kat MarchanNodejsFoundation
 
Node.js Core State of the Union- James Snell
Node.js Core State of the Union- James SnellNode.js Core State of the Union- James Snell
Node.js Core State of the Union- James SnellNodejsFoundation
 
From Pterodactyls and Cactus to Artificial Intelligence - Ivan Seidel Gomes, ...
From Pterodactyls and Cactus to Artificial Intelligence - Ivan Seidel Gomes, ...From Pterodactyls and Cactus to Artificial Intelligence - Ivan Seidel Gomes, ...
From Pterodactyls and Cactus to Artificial Intelligence - Ivan Seidel Gomes, ...NodejsFoundation
 
Multimodal Interactions & JS: The What, The Why and The How - Diego Paez, Des...
Multimodal Interactions & JS: The What, The Why and The How - Diego Paez, Des...Multimodal Interactions & JS: The What, The Why and The How - Diego Paez, Des...
Multimodal Interactions & JS: The What, The Why and The How - Diego Paez, Des...NodejsFoundation
 
Real-Life Node.js Troubleshooting - Damian Schenkelman, Auth0
Real-Life Node.js Troubleshooting - Damian Schenkelman, Auth0Real-Life Node.js Troubleshooting - Damian Schenkelman, Auth0
Real-Life Node.js Troubleshooting - Damian Schenkelman, Auth0NodejsFoundation
 
Developing Nirvana - Corey A. Butler, Author.io
Developing Nirvana - Corey A. Butler, Author.ioDeveloping Nirvana - Corey A. Butler, Author.io
Developing Nirvana - Corey A. Butler, Author.ioNodejsFoundation
 
Are your v8 garbage collection logs speaking to you?Joyee Cheung -Alibaba Clo...
Are your v8 garbage collection logs speaking to you?Joyee Cheung -Alibaba Clo...Are your v8 garbage collection logs speaking to you?Joyee Cheung -Alibaba Clo...
Are your v8 garbage collection logs speaking to you?Joyee Cheung -Alibaba Clo...NodejsFoundation
 
Node's Event Loop From the Inside Out - Sam Roberts, IBM
Node's Event Loop From the Inside Out - Sam Roberts, IBMNode's Event Loop From the Inside Out - Sam Roberts, IBM
Node's Event Loop From the Inside Out - Sam Roberts, IBMNodejsFoundation
 
Real-Time Machine Learning with Node.js - Philipp Burckhardt, Carnegie Mellon...
Real-Time Machine Learning with Node.js - Philipp Burckhardt, Carnegie Mellon...Real-Time Machine Learning with Node.js - Philipp Burckhardt, Carnegie Mellon...
Real-Time Machine Learning with Node.js - Philipp Burckhardt, Carnegie Mellon...NodejsFoundation
 
Math in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
Math in V8 is Broken and How We Can Fix It - Athan Reines, FourierMath in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
Math in V8 is Broken and How We Can Fix It - Athan Reines, FourierNodejsFoundation
 
Web MIDI API - the paster, the present, and the future -
Web MIDI API - the paster, the present, and the future -Web MIDI API - the paster, the present, and the future -
Web MIDI API - the paster, the present, and the future -Takashi Toyoshima
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8amix3k
 
IBM MQ v8 and JMS 2.0
IBM MQ v8 and JMS 2.0IBM MQ v8 and JMS 2.0
IBM MQ v8 and JMS 2.0Matthew White
 
Nodifying the Enterprise - Prince Soni, TO THE NEW
Nodifying the Enterprise - Prince Soni, TO THE NEWNodifying the Enterprise - Prince Soni, TO THE NEW
Nodifying the Enterprise - Prince Soni, TO THE NEWNodejsFoundation
 
Text Mining with Node.js - Philipp Burckhardt, Carnegie Mellon University
Text Mining with Node.js - Philipp Burckhardt, Carnegie Mellon UniversityText Mining with Node.js - Philipp Burckhardt, Carnegie Mellon University
Text Mining with Node.js - Philipp Burckhardt, Carnegie Mellon UniversityNodejsFoundation
 
Building Scalable Web Applications Using Microservices Architecture and NodeJ...
Building Scalable Web Applications Using Microservices Architecture and NodeJ...Building Scalable Web Applications Using Microservices Architecture and NodeJ...
Building Scalable Web Applications Using Microservices Architecture and NodeJ...NodejsFoundation
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterSimen Li
 
Express State of the Union at Nodejs Interactive EU- Doug Wilson
Express State of the Union at Nodejs Interactive EU- Doug WilsonExpress State of the Union at Nodejs Interactive EU- Doug Wilson
Express State of the Union at Nodejs Interactive EU- Doug WilsonNodejsFoundation
 
Workshop: Science Meets Industry: Online Behavioral Experiments with nodeGame...
Workshop: Science Meets Industry: Online Behavioral Experiments with nodeGame...Workshop: Science Meets Industry: Online Behavioral Experiments with nodeGame...
Workshop: Science Meets Industry: Online Behavioral Experiments with nodeGame...NodejsFoundation
 

En vedette (20)

Hitchhiker's Guide to"'Serverless" Javascript - Steven Faulkner, Bustle
Hitchhiker's Guide to"'Serverless" Javascript - Steven Faulkner, BustleHitchhiker's Guide to"'Serverless" Javascript - Steven Faulkner, Bustle
Hitchhiker's Guide to"'Serverless" Javascript - Steven Faulkner, Bustle
 
State of the CLI- Kat Marchan
State of the CLI- Kat MarchanState of the CLI- Kat Marchan
State of the CLI- Kat Marchan
 
Node.js Core State of the Union- James Snell
Node.js Core State of the Union- James SnellNode.js Core State of the Union- James Snell
Node.js Core State of the Union- James Snell
 
From Pterodactyls and Cactus to Artificial Intelligence - Ivan Seidel Gomes, ...
From Pterodactyls and Cactus to Artificial Intelligence - Ivan Seidel Gomes, ...From Pterodactyls and Cactus to Artificial Intelligence - Ivan Seidel Gomes, ...
From Pterodactyls and Cactus to Artificial Intelligence - Ivan Seidel Gomes, ...
 
Multimodal Interactions & JS: The What, The Why and The How - Diego Paez, Des...
Multimodal Interactions & JS: The What, The Why and The How - Diego Paez, Des...Multimodal Interactions & JS: The What, The Why and The How - Diego Paez, Des...
Multimodal Interactions & JS: The What, The Why and The How - Diego Paez, Des...
 
Real-Life Node.js Troubleshooting - Damian Schenkelman, Auth0
Real-Life Node.js Troubleshooting - Damian Schenkelman, Auth0Real-Life Node.js Troubleshooting - Damian Schenkelman, Auth0
Real-Life Node.js Troubleshooting - Damian Schenkelman, Auth0
 
Developing Nirvana - Corey A. Butler, Author.io
Developing Nirvana - Corey A. Butler, Author.ioDeveloping Nirvana - Corey A. Butler, Author.io
Developing Nirvana - Corey A. Butler, Author.io
 
Are your v8 garbage collection logs speaking to you?Joyee Cheung -Alibaba Clo...
Are your v8 garbage collection logs speaking to you?Joyee Cheung -Alibaba Clo...Are your v8 garbage collection logs speaking to you?Joyee Cheung -Alibaba Clo...
Are your v8 garbage collection logs speaking to you?Joyee Cheung -Alibaba Clo...
 
Node's Event Loop From the Inside Out - Sam Roberts, IBM
Node's Event Loop From the Inside Out - Sam Roberts, IBMNode's Event Loop From the Inside Out - Sam Roberts, IBM
Node's Event Loop From the Inside Out - Sam Roberts, IBM
 
Real-Time Machine Learning with Node.js - Philipp Burckhardt, Carnegie Mellon...
Real-Time Machine Learning with Node.js - Philipp Burckhardt, Carnegie Mellon...Real-Time Machine Learning with Node.js - Philipp Burckhardt, Carnegie Mellon...
Real-Time Machine Learning with Node.js - Philipp Burckhardt, Carnegie Mellon...
 
Math in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
Math in V8 is Broken and How We Can Fix It - Athan Reines, FourierMath in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
Math in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
 
Web MIDI API - the paster, the present, and the future -
Web MIDI API - the paster, the present, and the future -Web MIDI API - the paster, the present, and the future -
Web MIDI API - the paster, the present, and the future -
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
IBM MQ v8 and JMS 2.0
IBM MQ v8 and JMS 2.0IBM MQ v8 and JMS 2.0
IBM MQ v8 and JMS 2.0
 
Nodifying the Enterprise - Prince Soni, TO THE NEW
Nodifying the Enterprise - Prince Soni, TO THE NEWNodifying the Enterprise - Prince Soni, TO THE NEW
Nodifying the Enterprise - Prince Soni, TO THE NEW
 
Text Mining with Node.js - Philipp Burckhardt, Carnegie Mellon University
Text Mining with Node.js - Philipp Burckhardt, Carnegie Mellon UniversityText Mining with Node.js - Philipp Burckhardt, Carnegie Mellon University
Text Mining with Node.js - Philipp Burckhardt, Carnegie Mellon University
 
Building Scalable Web Applications Using Microservices Architecture and NodeJ...
Building Scalable Web Applications Using Microservices Architecture and NodeJ...Building Scalable Web Applications Using Microservices Architecture and NodeJ...
Building Scalable Web Applications Using Microservices Architecture and NodeJ...
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitter
 
Express State of the Union at Nodejs Interactive EU- Doug Wilson
Express State of the Union at Nodejs Interactive EU- Doug WilsonExpress State of the Union at Nodejs Interactive EU- Doug Wilson
Express State of the Union at Nodejs Interactive EU- Doug Wilson
 
Workshop: Science Meets Industry: Online Behavioral Experiments with nodeGame...
Workshop: Science Meets Industry: Online Behavioral Experiments with nodeGame...Workshop: Science Meets Industry: Online Behavioral Experiments with nodeGame...
Workshop: Science Meets Industry: Online Behavioral Experiments with nodeGame...
 

Similaire à Take Data Validation Seriously - Paul Milham, WildWorks

Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Nodejs functional programming and schema validation lightning talk
Nodejs   functional programming and schema validation lightning talkNodejs   functional programming and schema validation lightning talk
Nodejs functional programming and schema validation lightning talkDeepank Gupta
 
MBL203 Building a Mobile Application Platform on AWS - AWS re: Invent 2012
MBL203 Building a Mobile Application Platform on AWS - AWS re: Invent 2012MBL203 Building a Mobile Application Platform on AWS - AWS re: Invent 2012
MBL203 Building a Mobile Application Platform on AWS - AWS re: Invent 2012Amazon Web Services
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Security Bootcamp 2013 lap trinh web an toan
Security Bootcamp 2013   lap trinh web an toanSecurity Bootcamp 2013   lap trinh web an toan
Security Bootcamp 2013 lap trinh web an toanSecurity Bootcamp
 
Security Bootcamp 2013 - Lap trinh web an toan
Security Bootcamp 2013 - Lap trinh web an toanSecurity Bootcamp 2013 - Lap trinh web an toan
Security Bootcamp 2013 - Lap trinh web an toanSecurity Bootcamp
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...BradNeuberg
 
Secure .NET programming
Secure .NET programmingSecure .NET programming
Secure .NET programmingAnte Gulam
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Secure code
Secure codeSecure code
Secure codeddeogun
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by expressShawn Meng
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldChristian Melchior
 

Similaire à Take Data Validation Seriously - Paul Milham, WildWorks (20)

Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Nodejs functional programming and schema validation lightning talk
Nodejs   functional programming and schema validation lightning talkNodejs   functional programming and schema validation lightning talk
Nodejs functional programming and schema validation lightning talk
 
MBL203 Building a Mobile Application Platform on AWS - AWS re: Invent 2012
MBL203 Building a Mobile Application Platform on AWS - AWS re: Invent 2012MBL203 Building a Mobile Application Platform on AWS - AWS re: Invent 2012
MBL203 Building a Mobile Application Platform on AWS - AWS re: Invent 2012
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Node.js
Node.jsNode.js
Node.js
 
Security Bootcamp 2013 lap trinh web an toan
Security Bootcamp 2013   lap trinh web an toanSecurity Bootcamp 2013   lap trinh web an toan
Security Bootcamp 2013 lap trinh web an toan
 
Security Bootcamp 2013 - Lap trinh web an toan
Security Bootcamp 2013 - Lap trinh web an toanSecurity Bootcamp 2013 - Lap trinh web an toan
Security Bootcamp 2013 - Lap trinh web an toan
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
 
Secure .NET programming
Secure .NET programmingSecure .NET programming
Secure .NET programming
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Secure code
Secure codeSecure code
Secure code
 
NodeJS
NodeJSNodeJS
NodeJS
 
Security in Node.JS and Express:
Security in Node.JS and Express:Security in Node.JS and Express:
Security in Node.JS and Express:
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 

Dernier

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 

Dernier (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 

Take Data Validation Seriously - Paul Milham, WildWorks

  • 1.
  • 5. Outline • Attacks • Data Validation => Security • Data Normalization => Stability • Joi • Tean • Express Integration • Hapi Integration • Questions
  • 6. Safety • My job is to keep kids safe. • How do we keep our application safe? • Safe from what?
  • 7. Attacks • The web is full of jerks • https://www.owasp.org/index.php/Category:Attack • Read that for a bedtime horror story
  • 8. SQL Injection console.log(name); // paul console.log(email); // '); DROP TABLE db.user; -- mysql.query(`INSERT INTO db.user (name, email) VALUES ('${name}', '${email}')`);
  • 9. Shell Injection console.log(pass); // "; rm -rf /" require("child_process").exec(` php -r "print crypt('${pass}','$1$rounds=1$salt$');" `, (err, stdout, stderr) => { }); // hopefully you're using containers
  • 10. ReDOS const msg = 'foo=bar' + ';'.repeat(65535) + 'domain=example.com'; console.time("regex"); console.log(msg.search(/;+$/)); console.timeEnd("regex"); // regex: 5854.071ms :( • This is a sample vulnerability in tough cookie • https://snyk.io/vuln/npm:tough-cookie:20160722 • Be careful of "evil" regex
  • 11. Security • It’s a scary world • Security is important • There’s a lot more than just those three
  • 12. Validation • Verify the shape of the data • Malicious data can’t get in • First line of defense
  • 13. Simple Joi "use strict"; const Joi = require("joi"); Joi.validate("srsly a string", Joi.string(), (err, value) => { console.log(err); // null console.log(value); // "srsly a string" });
  • 14. Joi Failure Joi.validate(5, Joi.string(), (err, value) => { console.log(err); // Error console.log(value); // 5 });
  • 15. Joi Schema const schema = Joi.object().keys({ username: Joi.string().email({tldWhiteList: ["wildworks"]}).required(), password: Joi.string().min(6).max(25).required(), }); Joi.validate({ username: "paul.milham@wildworks.com", password: "justinbieber", }, schema, (err, value) => { console.log(err); console.log(value); });
  • 16. All In const schema = Joi.object().keys({ username: Joi.string().email({tldWhiteList: ["wildworks"]}).required(), }); Joi.validate({ username: "paul.milham@wildworks.com", password: "justinbieber", }, schema, (err, value) => { console.log(err); // justinbieber is not allowed });
  • 17. All In • Validating one field means validating them all • Hard for devs to forget
  • 18. Data Normalization • Normalization is being a good citizen • Normalization creates a contract with your consumer • Normalization goes a lot deeper than this (we'll get to that later)
  • 19. Joi Conversion Joi.validate("1.916", Joi.number(), (err, value) => { console.log(value.toFixed(1)); // 1.9 (No TypeError!) });
  • 20. Joi Defaults Joi.validate(undefined, Joi.number().default(0), (err, value) => { console.log(value.toFixed(1)); // 0.0 (No TypeError!) });
  • 21. Tean •Declarative syntax (schemas are POJOs) •Async •Convert data into models •Strict by default •https://www.npmjs.com/package/tean •Note that custom validators were recently added to Joi
  • 22. Tean Validation // simple validation tean.object({animal: "string"}, {animal: “kangaroo”}, (isValid, result) => { console.log(isValid); // true console.log(result); // {animal: "kangaroo"} });
  • 23. Tean Failure tean.object({animal: "string"}, {animal: null}, (isValid, result) => { console.log(isValid); // false console.log(result); // ["animal (null) is not a string"] });
  • 24. Tean Normalization // optional parameters tean.object({animal: “string(kangaroo,tiger)=tiger”, sparkles: "bool=true"}, {animal: "tiger"}, (isValid, result) => { console.log(isValid); // true console.log(result); // {animal: "tiger", sparkles: true} // Note that the original object is not altered! Normalized and validated data is passed into "result" in the callback });
  • 25. Model Mapping tean.object(req.body.params, { accessory: "avatarAccessory", user: ["userUid"], }, (isValid, result) => { });
  • 26. Data Normalization • Provides a friendly API • Provides consistency and reliability • Eliminates lots of common bugs
  • 27. Express • Everyone uses it! • No built in validation! • Too many exclamation points! • https://expressjs.com/
  • 28. Express + Joi app.get('/:username', function (req, res) { const schema = Joi.object().keys({ username: Joi.string().required(), }); Joi.validate(req.params, schema, (err, value) => { console.log(err); req.params = value; res.send(`${req.params.username} is the best!`); }); });
  • 29. Express + Tean app.get('/:user', function (req, res) { tean.object(req.body.params, { user: "userUid", }, (isValid, result) => { console.log(isValid); req.params = result; res.send(`${result.user.name} is the best!`); }); });
  • 30. Problem • We’re relying on the developer to remember to validate • This is a problem for maintenance and updates • Middleware to the rescue!
  • 31. Route Middleware this.app.post(options.route, tean.expressRequest(options.paramMap), (req, res) => { // do stuff options.handler(req.safeData, req, res); }, (err, req, res) => { console.log(err.stack); res.status(500).send(); } );
  • 32. Express + Joi • https://www.npmjs.com/package/celebrate
  • 33. Hapi • Hapi isn't minimalist like Express • Lots of options out of the box • http://hapijs.com/
  • 34. Hapi Validation app.route({ method: "POST", path: "/", config: { handler: (req, reply) => { reply("hey!"); }, validate: { payload: { username: Joi.string().email().required(), password: Joi.string().max(25).required(), }, }, }, });
  • 35. Take Away • FORCE validation of data - an opt in system isn't good enough • Make sure shape of data is acceptable • No validation, no data • This ensures malicious data does not enter your application
  • 36. Take Away • FORCE normalization of data shape • Data should always have a consistent shape • Make data access and usage reliable • Eliminates lots of “stupid” bugs
  • 37. On the Way Out • Have you thought about data security on the way out? • Mind blown! • Prevent Data Leaks from "heartbleed" or SQL Injection • Provide same stability contract for your client app