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

First version #1

Merged
merged 22 commits into from
Nov 12, 2024
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
6 changes: 6 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
40 changes: 40 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: CI

on:
pull_request:
push:
branches: main

jobs:
generate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- id: generate
uses: freckle/stack-action/generate-matrix@v5
outputs:
stack-yamls: ${{ steps.generate.outputs.stack-yamls }}

test:
runs-on: ubuntu-latest
needs: generate

strategy:
matrix:
stack-yaml: ${{ fromJSON(needs.generate.outputs.stack-yamls) }}
fail-fast: false

steps:
- uses: actions/checkout@v4
- uses: freckle/stack-action@v4
with:
stack-yaml: ${{ matrix.stack-yaml }}

lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: haskell-actions/hlint-setup@v2
- uses: haskell-actions/hlint-run@v2
with:
fail-on: warning
18 changes: 18 additions & 0 deletions .github/workflows/mergeabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: Mergeabot

on:
pull_request:
schedule:
- cron: "0 0 * * *"

permissions:
contents: write
pull-requests: write

jobs:
mergeabot:
runs-on: ubuntu-latest
steps:
- uses: freckle/mergeabot-action@v1
with:
quarantine-days: -1
18 changes: 18 additions & 0 deletions .github/workflows/restyled.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: Restyled

on:
pull_request:

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
restyled:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: restyled-io/actions/setup@v4
- uses: restyled-io/actions/run@v4
with:
suggestions: true
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.stack-work
5 changes: 5 additions & 0 deletions .restyled.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
restylers:
- hlint
- fourmolu
- "!stylish-haskell"
- "*"
Empty file added CHANGELOG.md
Empty file.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2024 Renaissance Learning Inc

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.
114 changes: 114 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# WAI OpenAPI Middleware

Validates request and response bodies against your service's OpenAPI spec.

This is useful in a non-Servant web application, where OpenAPI specs cannot be
generated from the API implementation itself, and so must be maintained
manually.

## Usage

```hs
import Network.Wai (Middleware)
import Network.Wai.Middleware.OpenApi qualified as OpenApi

middleware :: Middleware
middleware =
thisMiddleware
. thatMiddleware
. OpenApi.validate openApi
. theOtherMiddleware

-- Defined in your /docs or /openapi.json Handler
openApi :: OpenApi
openApi = undefined
```

Default behavior:

- If a request body is invalid, a 400 is returned
- If a response body is invalid, a 500 is returned
- In both cases, the validation errors are included in the response body

This is useful if you,

1. Are confident your server is currently complying with spec
2. Trust your spec enough to reject all invalid-according-to-it requests
3. Trust your observability to catch the 5xx increase any future
response-validity bug would cause

If all or some of these are not true, see the next section.

## Configuring

The `validate` function is equivalent to,

```hs
validateRequests defaultOnRequestErrors
. validateResponses defaultOnResponseErrors
```

Where those "on" functions take the appropriate error type and return a
`Middleware`. The reason it returns a middleware is so that it can decide if it
should take over the response or let it run normally:

```hs
defaultOnRequestErrors :: RequestErrors -> Middleware
defaultOnRequestErrors = \case
RequestSchemaNotFound {} -> id -- respond normally
RequestIsNotJson {} -> id
RequestInvalid _ errs -> \_ _ respond ->
respond $ clientErrorResponse errs -- respond with an error
```

Implementing and using a function like this would be how you:

1. Decide to error on missing schema, etc
2. Change the shape of of the JSON errors
3. Emit non-JSON errors

## Evaluation

When first implementing this, you probably want to log invalid cases but still
respond normally. To support this use-case, the library ships replacements for
`defaultOn*` that are named `evaluateOn*`. These functions take an action to
apply to the errors (presumably to log them) and then responds normally.

```hs
validateRequests (evaluateOnRequestErrors logIt)
. validateResponses (evaluateOnResponseErrors logIt)

logIt :: Show e => e -> IO ()
logIt = undefined
```

The action is necessarily `IO` because we're in a WAI middleware context.

## Performance & Sampling

This middleware may add a performance tax depending on the size of your typical
requests, responses, and OpenAPI spec itself. If you are concerned, we recommend
enabling this middleware on a sampling of requests.

For example,

```hs
openApiMiddleware :: OpenApi.Settings -> Middleware
openApiMiddleware settings =
-- Only validate 20% of requests
sampledMiddleware 20 $ OpenApi.validate spec

sampledMiddleware :: Int -> Middleware -> Middleware
sampledMiddleware percent m app request respond = do
roll <- randomRIO (0, 100)
if percent <= roll
then m app request respond
else app request respond
```

> [!NOTE]
> We will likely upstream `sampledMiddleware` to `wai-extra` at some point.

---

[CHANGELOG](./CHANGELOG.md) | [LICENSE](./LICENSE)
17 changes: 17 additions & 0 deletions fourmolu.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
indentation: 2
column-limit: 80 # ignored until v12 / ghc-9.6
function-arrows: leading
comma-style: leading # default
import-export-style: leading
indent-wheres: false # default
record-brace-space: true
newlines-between-decls: 1 # default
haddock-style: single-line
let-style: mixed
in-style: left-align
single-constraint-parens: never # ignored until v12 / ghc-9.6
unicode: never # default
respectful: true # default
fixities:
- "infix 4 `stringEqual`"
- "infixl 1 &"
97 changes: 97 additions & 0 deletions package.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
name: wai-middleware-openapi
version: 0.0.0.0
maintainer: Freckle Education
category: Web
synopsis: TODO
description: TODO

extra-doc-files:
- README.md
- CHANGELOG.md

ghc-options:
- -Weverything
- -Wno-all-missed-specialisations
- -Wno-missed-specialisations
- -Wno-missing-exported-signatures # re-enables missing-signatures
- -Wno-missing-import-lists
- -Wno-missing-local-signatures
- -Wno-monomorphism-restriction
- -Wno-safe
- -Wno-unsafe

when:
- condition: "impl(ghc >= 9.2)"
ghc-options:
- -Wno-missing-kind-signatures
- condition: "impl(ghc >= 8.10)"
ghc-options:
- -Wno-missing-safe-haskell-mode
- -Wno-prepositive-qualified-module

dependencies:
- base < 5

language: GHC2021

default-extensions:
- DataKinds
- DeriveAnyClass
- DerivingStrategies
- DerivingVia
- DuplicateRecordFields
- GADTs
- LambdaCase
- NoFieldSelectors
- NoImplicitPrelude
- NoMonomorphismRestriction
- NoPostfixOperators
- OverloadedRecordDot
- OverloadedStrings
- QuasiQuotes
- TypeFamilies

library:
source-dirs: src
dependencies:
- aeson
- bytestring
- filepath
- http-media
- http-types
- insert-ordered-containers
- lens
- mtl
- openapi3
- text
- wai

tests:
spec:
main: Spec.hs
source-dirs: tests
ghc-options: -threaded -rtsopts "-with-rtsopts=-N"
dependencies:
- aeson
- hspec
- http-types
- insert-ordered-containers
- lens
- openapi3
- text
- wai
- wai-extra
- wai-middleware-openapi

# readme:
# main: README.lhs
# ghc-options: -pgmL markdown-unlit
# dependencies:
# - Blammo
# - amazonka-core
# - amazonka-mtl
# - amazonka-s3
# - conduit
# - lens
# - markdown-unlit
# - mtl
Loading
Loading