SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
Take Data Validation
Seriously
Paul Milham, WildWorks
WildWorks
• I work there!
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(),
toolId: Joi.number().integer().required(),
});
Joi.validate({
username: "paul.milham@wildworks.com",
password: "justinbieber",
toolId: 9001,
}, 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
• https://www.npmjs.com/package/tean
• Tean should be considered experimental
• Note that custom validators were recently added to Joi
Tean Validation
// simple validation
tean.object({breakfast: "string"}, {breakfast: "bacon"}, (isValid,
result) => {
console.log(isValid); // true
console.log(result); // {breakfast: "bacon"}
});
Tean Failure
tean.object({breakfast: "string"}, {breakfast: null}, (isValid, result)
=> {
console.log(isValid); // false
console.log(result); // ["breakfast (null) is not a string"]
});
Tean Normalization
// optional parameters
tean.object({breakfast: “string(pancakes,waffles)?waffles”, addSyrup:
"bool?true"}, {breakfast: "pancakes"}, (isValid, result) => {
console.log(isValid); // true
console.log(result); // {breakfast: "pancakes", addSyrup: 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, {
language: "language",
pageTitle: "string?",
users: ["unifiedUserUid", "?[]"],
}, (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('/:pageId', function (req, res) {
const schema = Joi.object().keys({
pageId: Joi.number().min(0).required(),
});
Joi.validate(req.params, schema, (err, value) => {
console.log(err);
req.params = value;
res.send(`Hello World! ${req.params.pageId}`);
});
});
Express + Tean
app.get('/:pageId', function (req, res) {
tean.object(req.body.params, {
page: "page",
}, (isValid, result) => {
res.send(`Hello World! ${result.pageId}`);
});
});
Problem
• We’re relying on the developer to remember to
validate
• This is a problem for maintenance and updates
• Middleware to the rescue!
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 where
the developer can forget 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
• This makes 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 heartbleed (uninitialized buffer)
• Provide same stability contract for your client app (or
other consumer)
Bedankt!
• Any questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6
Technopark
 
Web осень 2012 лекция 6
Web осень 2012 лекция 6Web осень 2012 лекция 6
Web осень 2012 лекция 6
Technopark
 
Appengine Java Night #2a
Appengine Java Night #2aAppengine Java Night #2a
Appengine Java Night #2a
Shinichi Ogawa
 
Authentication
AuthenticationAuthentication
Authentication
soon
 

Was ist angesagt? (20)

Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web appsVelocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web apps
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 
Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6
 
Intro to PAS REST API
Intro to PAS REST APIIntro to PAS REST API
Intro to PAS REST API
 
Windows Server 2008 (PowerShell Scripting Uygulamaları)
Windows Server 2008 (PowerShell Scripting Uygulamaları)Windows Server 2008 (PowerShell Scripting Uygulamaları)
Windows Server 2008 (PowerShell Scripting Uygulamaları)
 
HTML5 JavaScript APIs
HTML5 JavaScript APIsHTML5 JavaScript APIs
HTML5 JavaScript APIs
 
Web осень 2012 лекция 6
Web осень 2012 лекция 6Web осень 2012 лекция 6
Web осень 2012 лекция 6
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and Ruby
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
Behind the curtain - How Django handles a request
Behind the curtain - How Django handles a requestBehind the curtain - How Django handles a request
Behind the curtain - How Django handles a request
 
Appengine Java Night #2a
Appengine Java Night #2aAppengine Java Night #2a
Appengine Java Night #2a
 
Javascript call ObjC
Javascript call ObjCJavascript call ObjC
Javascript call ObjC
 
Presentation
PresentationPresentation
Presentation
 
Working with AFNetworking
Working with AFNetworkingWorking with AFNetworking
Working with AFNetworking
 
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
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
Jquery-overview
Jquery-overviewJquery-overview
Jquery-overview
 
Authentication
AuthenticationAuthentication
Authentication
 
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
 
Leveraging parse.com for Speedy Development
Leveraging parse.com for Speedy DevelopmentLeveraging parse.com for Speedy Development
Leveraging parse.com for Speedy Development
 

Ähnlich wie 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 2012
Michelangelo 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 toan
Security 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 toan
Security Bootcamp
 

Ähnlich wie Take Data Validation Seriously - Paul Milham, WildWorks (20)

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
 
Node.js
Node.jsNode.js
Node.js
 
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
 
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
 
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
 
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 ...
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
 
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...
 
Owasp.meet up.2017.ppt
Owasp.meet up.2017.pptOwasp.meet up.2017.ppt
Owasp.meet up.2017.ppt
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
NodeJS
NodeJSNodeJS
NodeJS
 
PHPUG Presentation
PHPUG PresentationPHPUG Presentation
PHPUG Presentation
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
KISSY 的昨天、今天与明天
KISSY 的昨天、今天与明天KISSY 的昨天、今天与明天
KISSY 的昨天、今天与明天
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 

Mehr von NodejsFoundation

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
 

Mehr von NodejsFoundation (20)

The Morality of Code - Glen Goodwin, SAS Institute, inc.
The Morality of Code - Glen Goodwin, SAS Institute, inc.The Morality of Code - Glen Goodwin, SAS Institute, inc.
The Morality of Code - Glen Goodwin, SAS Institute, inc.
 
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
 
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
 
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...
 
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
 
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
 
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
 
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...
 
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...
 
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, ...
 
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...
 
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
 
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
 
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...
 
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
 
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, ...
 
Breaking Down the Monolith - Peter Marton, RisingStack
Breaking Down the Monolith - Peter Marton, RisingStackBreaking Down the Monolith - Peter Marton, RisingStack
Breaking Down the Monolith - Peter Marton, RisingStack
 
The Enterprise Case for Node.js
The Enterprise Case for Node.jsThe Enterprise Case for Node.js
The Enterprise Case for Node.js
 

Kürzlich hochgeladen

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Kürzlich hochgeladen (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

Take Data Validation Seriously - Paul Milham, WildWorks

  • 4. Outline • Attacks • Data Validation => Security • Data Normalization => Stability • Joi • Tean • Express Integration • Hapi Integration • Questions
  • 5. Safety • My job is to keep kids safe. • How do we keep our application safe? • Safe from what?
  • 6. Attacks • The web is full of jerks • https://www.owasp.org/index.php/Category:Attack • Read that for a bedtime horror story
  • 7. SQL Injection console.log(name); // paul console.log(email); // '); DROP TABLE db.user; -- mysql.query(`INSERT INTO db.user (name, email) VALUES ('${name}', '$ {email}')`);
  • 8. 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
  • 9. 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
  • 10. Security • It’s a scary world • Security is important • There’s a lot more than just those three
  • 11. Validation • Verify the shape of the data • Malicious data can’t get in • First line of defense
  • 12. 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" });
  • 13. Joi Failure Joi.validate(5, Joi.string(), (err, value) => { console.log(err); // Error console.log(value); // 5 });
  • 14. Joi Schema const schema = Joi.object().keys({ username: Joi.string().email({tldWhiteList: ["wildworks"]}).required(), password: Joi.string().min(6).max(25).required(), toolId: Joi.number().integer().required(), }); Joi.validate({ username: "paul.milham@wildworks.com", password: "justinbieber", toolId: 9001, }, schema, (err, value) => { console.log(err); console.log(value); });
  • 15. 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 });
  • 16. All In • Validating one field means validating them all • Hard for devs to forget
  • 17. 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)
  • 18. Joi Conversion Joi.validate("1.916", Joi.number(), (err, value) => { console.log(value.toFixed(1)); // 1.9 (No TypeError!) });
  • 19. Joi Defaults Joi.validate(undefined, Joi.number().default(0), (err, value) => { console.log(value.toFixed(1)); // 0.0 (No TypeError!) });
  • 20. Tean • Declarative syntax (schemas are POJOs) • Async • Convert data into models • https://www.npmjs.com/package/tean • Tean should be considered experimental • Note that custom validators were recently added to Joi
  • 21. Tean Validation // simple validation tean.object({breakfast: "string"}, {breakfast: "bacon"}, (isValid, result) => { console.log(isValid); // true console.log(result); // {breakfast: "bacon"} });
  • 22. Tean Failure tean.object({breakfast: "string"}, {breakfast: null}, (isValid, result) => { console.log(isValid); // false console.log(result); // ["breakfast (null) is not a string"] });
  • 23. Tean Normalization // optional parameters tean.object({breakfast: “string(pancakes,waffles)?waffles”, addSyrup: "bool?true"}, {breakfast: "pancakes"}, (isValid, result) => { console.log(isValid); // true console.log(result); // {breakfast: "pancakes", addSyrup: true} // Note that the original object is not altered! Normalized and validated data is passed into "result" in the callback });
  • 24. Model Mapping tean.object(req.body.params, { language: "language", pageTitle: "string?", users: ["unifiedUserUid", "?[]"], }, (isValid, result) => { });
  • 25. Data Normalization • Provides a friendly API • Provides consistency and reliability • Eliminates lots of common bugs
  • 26. Express • Everyone uses it! • No built in validation! • Too many exclamation points! • https://expressjs.com/
  • 27. Express + Joi app.get('/:pageId', function (req, res) { const schema = Joi.object().keys({ pageId: Joi.number().min(0).required(), }); Joi.validate(req.params, schema, (err, value) => { console.log(err); req.params = value; res.send(`Hello World! ${req.params.pageId}`); }); });
  • 28. Express + Tean app.get('/:pageId', function (req, res) { tean.object(req.body.params, { page: "page", }, (isValid, result) => { res.send(`Hello World! ${result.pageId}`); }); });
  • 29. Problem • We’re relying on the developer to remember to validate • This is a problem for maintenance and updates • Middleware to the rescue!
  • 30. Hapi • Hapi isn't minimalist like Express • Lots of options out of the box • http://hapijs.com/
  • 31. 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(), }, }, }, });
  • 32. Take Away • FORCE validation of data - an opt in system where the developer can forget isn't good enough • Make sure shape of data is acceptable • No validation, no data • This ensures malicious data does not enter your application
  • 33. Take Away • FORCE normalization of data shape • Data should always have a consistent shape • This makes data access and usage reliable • Eliminates lots of “stupid” bugs
  • 34. On the Way Out • Have you thought about data security on the way out? • Mind blown! • Prevent heartbleed (uninitialized buffer) • Provide same stability contract for your client app (or other consumer)