Skip to content
This repository has been archived by the owner on Sep 8, 2023. It is now read-only.

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mattt committed Sep 14, 2018
0 parents commit 2441341
Show file tree
Hide file tree
Showing 8 changed files with 428 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
@@ -0,0 +1,4 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
19 changes: 19 additions & 0 deletions LICENSE.md
@@ -0,0 +1,19 @@
Copyright 2018 Read Evaluate Press, LLC

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
28 changes: 28 additions & 0 deletions Package.swift
@@ -0,0 +1,28 @@
// swift-tools-version:4.2
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "ContentSecurityPolicy",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "ContentSecurityPolicy",
targets: ["ContentSecurityPolicy"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "ContentSecurityPolicy",
dependencies: []),
.testTarget(
name: "ContentSecurityPolicyTests",
dependencies: ["ContentSecurityPolicy"]),
]
)
84 changes: 84 additions & 0 deletions README.md
@@ -0,0 +1,84 @@
# ContentSecurityPolicy

A Swift library for defining
[Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)
header values.

---

## Requirements

- Swift 4.0+

## Installation

### Swift Package Manager

Add the ContentSecurityPolicy package to your target dependencies in `Package.swift`:

```swift
import PackageDescription

let package = Package(
name: "YourProject",
dependencies: [
.package(
url: "https://github.com/ReadEval/ContentSecurityPolicy",
from: "0.0.1"
),
]
)
```

Then run the `swift build` command to build your project.

### Carthage

To use ContentSecurityPolicy in your Xcode project using Carthage,
specify it in `Cartfile`:

```
github "ReadEval/ContentSecurityPolicy" ~> 0.0.1
```

Then run the `carthage update` command to build the framework,
and drag the built ContentSecurityPolicy.framework into your Xcode project.

## Usage

Create a `ContentSecurityPolicy` object
using the designated initializer;
each parameter has a default values,
so you can specify only the directives relevant to your use case:

```swift
import ContentSecurityPolicy

let csp = ContentSecurityPolicy(
defaultSrc: [.`self`],
baseURI: URL(string: "https://readeval.press")!,
upgradeInsecureRequests: true
)
csp.policy
// default-src: 'self'; base-uri: https://readeval.press; upgrade-insecure-requests
```

You can use the computed `policy` property value
to set the `"Content-Security-Policy"` header on HTTP response headers.
Here's how you might do this using Vapor:

```swift
import Vapor

let response = response ...
response.headers["Content-Security-Policy"] = csp.policy
```

## License

MIT

## Contact

Read Evaluate Press, LLC
([@ReadEvalPress](https://twitter.com/ReadEvalPress))
255 changes: 255 additions & 0 deletions Sources/ContentSecurityPolicy/ContentSecurityPolicy.swift
@@ -0,0 +1,255 @@
import Foundation

public struct ContentSecurityPolicy {
public typealias MIMEType = String

public struct Sources: Equatable, Hashable {
public enum Source: Equatable, Hashable {
public enum HashAlgorithm: String {
case sha256, sha384, sha512
}

case `self`
case unsafeInline
case unsafeEval
case strictDynamic
case scheme(String)
case host(String)
case nonce(String)
case hash(HashAlgorithm, Data)
}

public let value: String

public static var all: Sources {
return Sources(value: "*")
}

public static var none: Sources {
return Sources(value: "'none'")
}

public init(_ sources: [Source]) {
self.value = sources.map{ $0.description }.joined(separator: " ")
}

private init(value: String) {
self.value = value
}
}

/// default-src
public var defaultSrc: Sources?

/// base-uri
public var baseURI: URL?

/// child-src
public var childSrc: Sources?

/// connect-src
public var connectSrc: Sources?

/// font-src
public var fontSrc: Sources?

/// form-action
public var formAction: Sources?

/// frame-ancestors
public var frameAncestors: Sources?

/// frame-src
public var frameSrc: Sources?

/// img-src
public var imgSrc: Sources?

/// media-src
public var mediaSrc: Sources?

/// object-src
public var objectSrc: Sources?

/// plugin-types
public var pluginTypes: [MIMEType]?

/// report-uri
public var reportURI: URL?

/// srcipt-src
public var scriptSrc: Sources?

/// style-src
public var styleSrc: Sources?

/// upgrade-insecure-requests
public var upgradeInsecureRequests: Bool = false

/// worker-src
public var workerSrc: Sources?

public init(defaultSrc: Sources? = nil,
baseURI: URL? = nil,
childSrc: Sources? = nil,
connectSrc: Sources? = nil,
fontSrc: Sources? = nil,
formAction: Sources? = nil,
frameAncestors: Sources? = nil,
frameSrc: Sources? = nil,
imgSrc: Sources? = nil,
mediaSrc: Sources? = nil,
objectSrc: Sources? = nil,
pluginTypes: [MIMEType]? = nil,
reportURI: URL? = nil,
scriptSrc: Sources? = nil,
styleSrc: Sources? = nil,
upgradeInsecureRequests: Bool = false,
workerSrc: Sources? = nil)
{
self.defaultSrc = defaultSrc
self.baseURI = baseURI
self.childSrc = childSrc
self.connectSrc = connectSrc
self.fontSrc = fontSrc
self.formAction = formAction
self.frameAncestors = frameAncestors
self.frameSrc = frameSrc
self.imgSrc = imgSrc
self.mediaSrc = mediaSrc
self.objectSrc = objectSrc
self.pluginTypes = pluginTypes
self.reportURI = reportURI
self.scriptSrc = scriptSrc
self.styleSrc = styleSrc
self.upgradeInsecureRequests = upgradeInsecureRequests
self.workerSrc = workerSrc
}

public var policy: String {
var directives: [String] = []

if let defaultSrc = self.defaultSrc {
directives.append("default-src: \(defaultSrc)")
}

if let baseURI = self.baseURI {
directives.append("base-uri: \(baseURI.absoluteString)")
}

if let childSrc = self.childSrc {
directives.append("child-src: \(childSrc)")
}

if let connectSrc = self.connectSrc {
directives.append("connect-src: \(connectSrc)")
}

if let fontSrc = self.fontSrc {
directives.append("font-src: \(fontSrc)")
}

if let formAction = self.formAction {
directives.append("form-action: \(formAction)")
}

if let frameAncestors = self.frameAncestors {
directives.append("frame-ancestors: \(frameAncestors)")
}

if let frameSrc = self.frameSrc {
directives.append("frame-src: \(frameSrc)")
}

if let imgSrc = self.imgSrc {
directives.append("img-src: \(imgSrc)")
}

if let mediaSrc = self.mediaSrc {
directives.append("media-src: \(mediaSrc)")
}

if let objectSrc = self.objectSrc {
directives.append("object-src: \(objectSrc)")
}

if let pluginTypes = self.pluginTypes {
directives.append("plugin-types: \(pluginTypes.joined(separator: " "))")
}

if let reportURI = self.reportURI {
directives.append("report-uri: \(reportURI.absoluteString)")
}

if let scriptSrc = self.scriptSrc {
directives.append("script-src: \(scriptSrc)")
}

if let styleSrc = self.styleSrc {
directives.append("style-src: \(styleSrc)")
}

if self.upgradeInsecureRequests {
directives.append("upgrade-insecure-requests")
}

if let workerSrc = self.workerSrc {
directives.append("worker-src: \(workerSrc)")
}

return directives.joined(separator: "; ")
}
}

extension ContentSecurityPolicy: CustomStringConvertible {
public var description: String {
return policy
}
}

extension ContentSecurityPolicy: CustomDebugStringConvertible {
public var debugDescription: String {
return policy.split(separator: ";").joined(separator: ";\n")
}
}

extension ContentSecurityPolicy.Sources: CustomStringConvertible {
public var description: String {
return self.value
}
}

extension ContentSecurityPolicy.Sources: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Source...) {
self.init(elements)
}
}

extension ContentSecurityPolicy.Sources: ExpressibleByNilLiteral {
public init(nilLiteral: ()) {
self = .none
}
}

extension ContentSecurityPolicy.Sources.Source: CustomStringConvertible {
public var description: String {
switch self {
case .`self`:
return "'self'"
case .unsafeInline:
return "'unsafe-inline'"
case .unsafeEval:
return "'unsafe-eval'"
case .strictDynamic:
return "'strict-dynamic'"
case .scheme(let string):
return string
case .host(let string):
return string
case .nonce(let string):
return "'nonce-\(string)'"
case let .hash(algorithm, data):
return "'\(algorithm)-\(data.base64EncodedString())'"
}
}
}

0 comments on commit 2441341

Please sign in to comment.