Note that there are some explanatory texts on larger screens.

plurals
  1. POCompile-time constraints for strings in F#, similar to Units of Measure - is it possible?
    primarykey
    data
    text
    <p>I'm developing a Web application using F#. Thinking of protecting user input strings from SQL, XSS, and other vulnerabilities.</p> <p>In two words, I need some compile-time constraints that would allow me discriminate plain strings from those representing SQL, URL, XSS, XHTML, etc.</p> <p>Many languages have it, e.g. Ruby’s native string-interpolation feature <code>#{...}</code>.<br> With F#, it seems that Units of Measure do very well, but they are only available for numeric types.<br> There are several solutions employing <strong>runtime</strong> UoM <a href="http://trelford.com/blog/post/Runtime-Units-of-Measure-for-F.aspx" rel="noreferrer">(link)</a>, however I think it's an overhead for my goal.</p> <p>I've looked into FSharpPowerPack, and it seems quite possible to come up with something similar for strings:</p> <pre><code>[&lt;MeasureAnnotatedAbbreviation&gt;] type string&lt;[&lt;Measure&gt;] 'u&gt; = string // Similarly to Core.LanguagePrimitives.IntrinsicFunctions.retype [&lt;NoDynamicInvocation&gt;] let inline retype (x:'T) : 'U = (# "" x : 'U #) let StringWithMeasure (s: string) : string&lt;'u&gt; = retype s [&lt;Measure&gt;] type plain let fromPlain (s: string&lt;plain&gt;) : string = // of course, this one should be implemented properly // by invalidating special characters and then assigning a proper UoM retype s // Supposedly populated from user input let userName:string&lt;plain&gt; = StringWithMeasure "John'); DROP TABLE Users; --" // the following line does not compile let sql1 = sprintf "SELECT * FROM Users WHERE name='%s';" userName // the following line compiles fine let sql2 = sprintf "SELECT * FROM Users WHERE name='%s';" (fromPlain userName) </code></pre> <p><em>Note</em>: It's just a sample; don't suggest using <code>SqlParameter</code>. :-)</p> <p>My questions are: Is there a decent library that does it? Is there any possibility to add syntax sugar?<br> Thanks.</p> <p><strong>Update 1</strong>: I need compile-time constraints, thanks Daniel.</p> <p><strong>Update 2</strong>: I'm trying to avoid any runtime overhead (tuples, structures, discriminated unions, etc).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload